【发布时间】:2013-09-27 11:21:17
【问题描述】:
我在Contributor 和Resource 之间通过Contributorship 建立了has_many_through 关系。不同寻常的是,当我建立关联时,我需要为 :
contribution_type
model Contributor
has_many contributorships
has_many contributors, through: contributorships
end
model Resource
has_many contributorships
has_many resources, through: contributorships
end
model Contributorships
attr_accessible :contribution_type, :contributor, :archive_resource
belongs_to resources
belongs_to contributors
end
建立关联涉及:
c = Contributor.create!()
r = Resource.create!()
c.contributorships.create!(resource:r, contribution_type: :author)
或者(如果我不想提前保存):
c = Contributor.new()
r = Resource.new()
cs = Contributorship.new(contributor:c, resource:r, contribution_type: :author)
c.save!
r.save!
cs.save!
如果我不需要在 Contributorship 加入模型上设置 contribution_type 属性,我可以这样做:
c.resources << r
那么有没有更优雅的方式来做到这一点和同时设置属性?
【问题讨论】:
-
是什么类型的?随机字符串还是数组中的一组预定义值?
标签: ruby-on-rails ruby-on-rails-3 join model has-many-through