0

我通过a 在 a和 ahas_many_through之间建立了关系。不同寻常的是,当我建立关联时,我需要为:ContributorResourceContributorshipcontribution_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!

如果我不需要contribution_typeContributorship加入模型上设置属性,我可以这样做:

c.resources << r

那么有没有更优雅的方式来同时设置属性呢?

4

2 回答 2

1

您可以使用build自动设置实例化对象之间的关联。

contributor = Contributor.new
contributor.contributorships.build(:contribution_type => :author)
contributor.resources.build
contributor.save!
于 2013-09-27T11:40:31.333 回答
1

如果contributor_type 的值依赖于来自其他模型之一的值,我倾向于只编写一个 before_validation 回调来在每次创建 Contributorships 时设置正确的对应值。IE

model Contributorships

  attr_accessible :contribution_type, :contributor, :archive_resource

  belongs_to resources
  belongs_to contributors

  before_validation :set_contributor_type

  def set_contributor_type
     if self.new_record?
        # Whatever code you need to determine the type value
        self.contributor_type = value
     end
  end

end

如果相反,这是一个用户定义的值,那么您将需要使用accepts_nested_attributes_for在哪个模型中定义您的contributor_type,然后在表单中使用fields_for,以允许用户在创建记录时设置值。这在以下 railscast 中有非常全面和详细的介绍:http: //railscasts.com/episodes/197-nested-model-form-part-2?view=asciicast

IE:

<%= form_for(contributor) do |f| %>
   # Whatever fields you want to save for the contributor
   <% contributorship = f.object.contributorships.build %>
   <%= f.fields_for(:contributorships, contributorship) do |new_contributorship| %>
         # Whatever fields you want to save for the contributorship
         <% resource = new_contributorship.object.resources.build %>
         <%= f.fields_for(:resources, resource) do |new_resource| %>
                # Whatever fields you want to save for the resource
         <% end %>
   <% end %>
<% end %>
于 2013-09-27T11:45:27.127 回答