Rails 3数据建模帮助 - Has_many,属于嵌套属性

时间:2011-03-18 20:17:36

标签: ruby-on-rails ruby-on-rails-3 activerecord nested-forms nested-attributes

我正在开展涉及三个模型(收件人,奖励,播音员)的项目,并且当播音员向多个收件人发放奖励时需要具有嵌套属性。举个例子,奖励表格需要有能力做三件事:

  1. 可以添加多个收件人(即“添加收件人”,“删除收件人”) - 嵌套属性
  2. 创建新奖项后,该奖项将发布到收件人的个人资料中。
  3. 启用@ recipient.awards和@ announcer.awards
  4. 的未来轮询

    在如何巧妙地解决这个问题方面真的很挣扎。以下数据结构有意义,但不能在奖励表单中执行“accepts_nested_attributes_for:recipients”。你能帮我吗?非常感谢提前。

    类收件人<的ActiveRecord ::基

    • has_many:awards
    • has_many:播音员,:through => :奖励

    类播音员<的ActiveRecord ::基

    • has_many:awards
    • has_many:收件人,:via => :奖励

    班级奖<的ActiveRecord ::基

    • belongs_to:播音员
    • belongs_to:收件人

1 个答案:

答案 0 :(得分:3)

你就在那里。主要问题是您尝试在表单中创建收件人对象,而不是仅仅创建奖励与另一个对象(用户)之间的关系。你可以这样做:

class User < ActiveRecord::Base
  has_many :recipients
  has_many :awards, :through => :recipients
end

# this is your relationship between an award and a user
class Recipient < ActiveRecord::Base
  belongs_to :user
  belongs_to :award
end

class Award < ActiveRecord::Base
  has_many :recipients
  has_many :users, :through => :recipients
  belongs_to :announcer

  accepts_nested_attributes_for :recipients, :allow_destroy => true
end

class Announcer < ActiveRecord::Base
  has_many :awards
  has_many :recipients, :through => :awards
end

然后你只需要一个嵌套的表单来构建recipients_attributes数组:

<%= form_for @award do |f| %>

  <%= f.text_field :name %>

  <div id="recipients">
    <% @award.recipients.each do |recipient| %>

     <%= render :partial => '/recipients/new', :locals => {:recipient => recipient, :f => f} %>

    <% end %>
  </div>
  <%= link_to_function 'add recipient', "jQuery('#recipients').append(#{render(:partial => '/recipients/new').to_json})" %>

<% end %>

并且,为了保持DRY,只需将嵌套部分推入部分:

# app/views/recipients/_new.html.erb
<% recipient ||= Recipient.new %>
<%= f.fields_for 'recipients_attributes[]', recipient do |rf| %>
  <%= rf.select :user_id, User.all %>
  <%= fr.check_box '_delete' %>
  <%= fr.label '_delete', 'remove' %>
<% end %>

显然User.all调用并不理想,所以可能会自动完成。