Rails基本关联

时间:2011-10-14 22:21:41

标签: ruby-on-rails-3 ruby-on-rails-3.1

我正在尝试在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

2 个答案:

答案 0 :(得分:1)

根据您想要达到的目标,您的解决方案是正确的(或不是)。我看到以下情况:

  1. 您想在项目和用户之间创建n:m关联。因此,每个项目都可以被许多用户引用,并且每个用户都引用了许多项目。如果这是正确的背景,那么您的解决方案是正确的。有关详细信息,请参阅Rails Guides: Associations
  2. 这种情况的另一种选择可能是使用has_and_belongs_to_many Association。情况是一样的,但谈论列表是没有意义的,没有模型对象。
  3. 如果每个用户可能有多个列表,并且每个列表可能包含很多项,那么您的解决方案就会出错。这不是n:m与列表之间的关联作为中间的连接表,而是两个1:n关系。
  4. 第三个例子的代码如下:

    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,但是其他人(比如我)会不同意 - 使用正确的工具来做工作。