ruby-on-rails – 如何创建自动设置连接表属性的关联?
发布时间:2020-12-17 02:21:24 所属栏目:百科 来源:网络整理
导读:我对如何有效地使用我的关联的“轨道方式”感到困惑. 以下是Rails 4应用程序的示例模型配置: class Film ActiveRecord::Base # A movie,documentary,animated short,etc has_many :roleships has_many :participants,:through = :roleships has_many :roles
我对如何有效地使用我的关联的“轨道方式”感到困惑.
以下是Rails 4应用程序的示例模型配置: class Film < ActiveRecord::Base # A movie,documentary,animated short,etc has_many :roleships has_many :participants,:through => :roleships has_many :roles,:through => :roleships # has_many :writers........ ? end class Participant < ActiveRecord::Base # A human involved in making a movie has_many :roleships end class Role < ActiveRecord::Base # A person's role in a film. i.e. "Writer","Actor","Extra" etc has_many :roleships end class Roleship < ActiveRecord::Base # The join for connecting different people # to the different roles they have had in # different films belongs_to :participant belongs_to :film belongs_to :role end 鉴于上面的模型配置,我希望我拥有的代码允许我直接将编写器添加到电影中,并最终正确地进行连接设置. 所以,例如,我希望能够做到这样的事情: ## The Code I WISH I Had Film.create!(name: "Some film",writers: [Participant.first]) 我不确定我是否会考虑这完全错误,但似乎不可能.完成此任务的正确方法是什么?嵌套资源?自定义setter范围?别的什么?虚拟属性?谢谢! 解决方法
我根据您的问题创建了一个示例应用.
https://github.com/szines/hodor_filmdb 我认为通过关联在参与者和角色模型中设置也很有用,但如果没有这个就行了.这取决于您希望以后如何使用此数据库.没有通过此查询将无法工作:Participant.find(1).films class Participant < ActiveRecord::Base has_many :roleships has_many :films,through: :roleships end class Role < ActiveRecord::Base has_many :roleships has_many :films,through: :roleships end 不要忘记在films_controller.rb中为额外字段(strong_parameters)提供许可 def film_params params.require(:film).permit(:title,:participant_ids,:role_ids) end 奇怪的是,如果您创建一个具有参与者和角色的新电影,将在连接表中创建两条记录. 希望这有帮助,有人可以帮助我们进一步改进……如果您有任何疑问,请告诉我. 更新: 您可以在模型中创建一种虚拟属性.例如: def writers=(participant) @writer_role = Role.find(1) self.roles << @writer_role self.participants << participant end 你可以使用:Film.create(标题:’The Movie’,作家:[Participant.first]) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |