我正在尝试在rails中进行基本模型关联。 基本上我有一个List表来存储item_id和user_id。
一个用户可以创建多个“列表项”。
这是正确的方法吗?
感谢。
class Item < ActiveRecord::Base
has_many :users, :through => :lists
end
class User < ActiveRecord::Base
has_many :items, :through => :lists
end
class List < ActiveRecord::Base
belongs_to :user
belongs_to :item
end
答案 0 :(得分:1)
根据您想要达到的目标,您的解决方案是正确的(或不是)。我看到以下情况:
has_and_belongs_to_many
Association。情况是一样的,但谈论列表是没有意义的,没有模型对象。第三个例子的代码如下:
class User < ActiveRecord::Base
has_many :items, :through => :lists
has_many :lists
end
class List < ActiveRecord::Base
has_many :items
belongs_to :user
end
class Item < ActiveRecord::Base
belongs_to :list
end
在第一个解决方案中,您应该将用户的关系添加到列表和要列出的项目中:
class Item < ActiveRecord::Base
has_many :lists
has_many :users, :through => :lists
end
class User < ActiveRecord::Base
has_many :lists
has_many :items, :through => :lists
end
答案 1 :(得分:0)
如果“list”实体真的是一个纯粹的关联/连接,也就是说,它没有自己的固有属性,那么你可以简化一下并使用has_and_belongs_to_many。那你就不需要一个“List”类。
class Item < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :items
end
Rails将在“items_users”表中查找引用,因此在迁移中,您需要创建一个la:
create_table :items_users, :id => false do |t|
t.references :users, :items
end
很多人会告诉你总是使用has_many:through,但是其他人(比如我)会不同意 - 使用正确的工具来做工作。