2

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

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

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

类收件人 < ActiveRecord::Base

  • has_many : 奖项
  • has_many :announcers, :through => :awards

结尾

类播音员 < ActiveRecord::Base

  • has_many : 奖项
  • has_many :recipients, :through => :awards

结尾

类奖 < ActiveRecord::Base

  • 属于_to:播音员
  • 属于_to :recipient

结尾

4

1 回答 1

4

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

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 %>

而且,为了保持干燥,只需将嵌套部分推入部分:

# 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 调用并不理想,所以可能会自动完成。

于 2011-03-18T23:29:03.077 回答