我完全不知道我应该如何去有效地使用我的联想的“轨道方式”。
这是来自 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])
我不确定我是否要考虑完全错误的想法,但这似乎是不可能的。实现这一目标的正确方法是什么?嵌套资源?自定义设置器+范围?还有什么?虚拟属性?谢谢你!