我几乎没有什么问题需要回答。一切都和下面的教程有关Two Many-to-Many
问题一
使用has_many的join表需要有id吗?还是删除 id 的最佳做法?并添加一个索引并使用另外两个主键并将其设置为唯一且在一起?
问题2
创建表的迁移如何实现?
问题3
在完成这些关系模型和更新数据之后。我想在每次更新时创建一组新数据(以保留数据)。 Controller 在更新、新建、创建模型中的外观如何?
问题4
在中间表中,我想设置属性,例如具有可见的 true 或 false,我怎样才能不仅设置第三个表而且还设置第二个表参数
最佳答案
首先……提醒一句:railscast 非常古老。新版本的 rails 可能已经过时了那一集中的句法。
问题一
如果您正在使用 has_many through 方法,那么您必须在连接模型中有一个 id 列,因为您正在使用一个完整的模型。正如 Ryan 在该集中提到的,如果您需要跟踪其他信息,您将选择此方法。如果您使用 has_and_belongs_to_many 方法,您的表中将不会有 id 列。
如果您想在不允许多对多关联中出现重复项的情况下进行检查(即允许项目 a 与项目 b 配对并再次允许项目 a 到项目 b 的另一条记录),您可以使用一个简单的验证具有范围的行:
validates_uniqueness_of :model_a_id, :scope => [:model_b_id]
问题2
您可以使用此代码在迁移中添加索引
add_index :table_name, [ :join_a_id, :join_b_id ], :unique => true, :name => 'by_a_and_b'
这将被插入到您的 create_table 语句下方的更改 block 中(但不在该 create_table block 中)。查看此问题以获取更多详细信息:In a join table, what's the best workaround for Rails' absence of a composite key?
问题3
我不是很清楚你想要完成什么,但如果你想在每次将新记录插入连接模型时采取一些行动,我会使用 after_create 事件记录 Hook 。这看起来像这样。
class YourJoinModel < ActiveRecord::Base
after_create :do_something
def do_something
puts "hello world"
end
end
每次创建新记录时都会调用该函数 do_something。
问题4
使用 has_many through 方法将使您能够访问您在该模型中在关系两侧定义的附加属性。例如,如果您有此设置:
class Factory < ActiveRecord::Base
has_many :widgets, :through => :showcases
end
class Widget < ActiveRecord::Base
has_many :factories, :through => :showcases
end
class Showcases < ActiveRecord::Base
belongs_to :factory
belongs_to :widget
attr_accessiable :factory_id, :widget_id, :visible
end
你可以这样说
widget = Widget.first
shown = widget.showcases
shown.first.visible
或
shown = widget.showcases.where( :visible=> true )
您还可以联系其他协会:
shown.first.factory
关于ruby-on-rails - Rails 有很多关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11723012/