我有三个模型,Model,ModelType和ModelCategory。它们通过关联表(例如ModelTypeRelationship和)相互连接ModelCategoryRelationship。
# app/models/model.rb
class Model < ActiveRecord::Base
has_many :model_type_relationships, dependent: :destroy
has_many :model_category_relationships, dependent: :destroy
has_many :types, through: :model_type_relationships
has_many :categories, through: :model_category_relationships
...
end
注意:将返回与关联model1.type的对象数组。可能与多个或相关联。ModelTypemodel1modelsmodel_typesmodel_categories
我希望能够选择一个随机Model数,使其属于type1和category1。
Model我在选择 a of方面取得了一些成功type1,但在那之后我陷入了困境。这是我的选择代码:
ModelType.find_by_name("type1").models.find(:first, :order => "Random()")
注意:返回一个对象model_type1.models数组。Modeltype1