2013-04-29 42 views
0

如果我建立了以下模型,是否在Authorship表中添加属性foo,这是特定于该关系的属性,而不是其他属性?如何在多对多表中发布和访问信息

class Author < ActiveRecord::Base 
    has_many :authorships 
    has_many :books, :through => :authorships 
end 

class Book < ActiveRecord::Base 
    has_many :authorships 
    has_many :authors, :through => :authorships 
end 

class Authorship < ActiveRecord::Base 
    attr_accessible :foo 

    belongs_to :author 
    belongs_to :book 
end 

什么查询会返回:foo属性,还是有更好的方法呢?

回答

0

使用has_many :through时,向中间模型添加属性是完全合适的。这是使用该模式而不是has_and_belongs_to_many的主要原因之一。

除了你已经证明了什么(attr_accessible),你还需要通过实际迁移属性添加到表:

class AddFooToAuthorships < ActiveRecord::Migration 
    def change 
    add_column :authorships, :foo, :text 
    end 
end 

至于查询...我想这取决于你”重新尝试去做。例如,@book.authorships.pluck(:foo)将返回关于与特定书籍相关的作者的所有foo的值。

+0

我已经完成了迁移,我只是不确定如何实际访问这些信息,或者如果这是存储信息的正确方法。您的回答提供了我需要的所有清晰度,谢谢! – Sean 2013-04-29 21:01:53