我对我应该如何去关于有效使用我的关联的“轨道方式”完全感到困惑。如何创建一个自动设置连接表属性的关联?
下面是从一个轨道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 +范围?还有别的吗?虚拟属性?谢谢!
这岂不是有不利影响的道路?例如,如果有嵌套表单(即从视图中构建电影),那么这将全部被推入一个胖子控制器中?另外,正如我所提到的,这是一个rails4应用程序(使用强参数) – Hodor
您可以将角色的创建推送到模型,然后您必须将所有必要的参数传递给该创建函数。这样你就可以用某种“自定义嵌套属性”来构建表单 –
我想我在概念上理解,但我无法准确设想代码的样子。 – Hodor