【问题标题】:issue with editing model using accepts_nested_attributes_for使用 accept_nested_attributes_for 编辑模型的问题
【发布时间】:2011-11-19 16:14:07
【问题描述】:

我有三个模型——捐赠者、接受者和礼物,

捐助者模型 - has_one :recipient,belongs_to :gift,accepts_nested_attributes_for,:recipient,accepts_nested_attributes_for :gift

接受者模型 - belongs_to :donor

还有礼物模型 - has_many :donors

当用户在显示页面 - /donors/1 - 我希望能够编辑收件人并添加礼物。他们正在从一个表单中编辑所有三个模型。

我在控制器中的显示操作是提供一个表单,通过@recipient = @donor.build_recipient 在该表单上添加一个收件人 - 我在视图中设置了表单。这行得通!

但是我试图允许用户通过选择框将预先存在的礼物附加给用户 -

<%= select(:gift, :gift_id, Gift.all.collect {|p| [ p.name, p.id ] },  {:prompt => 'Select gift'}) %>

这将显示一个选择框,其中包含表格中列出的所有礼物。

当我提交表单时,我可以编辑捐赠者的详细信息,添加收件人,但礼物模型(或捐赠者与礼物的关系)根本没有更新。我做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord model associations


    【解决方案1】:

    我相信你需要这样的东西:

    <% form_for @donor do |f| %>
    
      ...
    
      <% f.select :gift_id, Gift.all.map{ |p| [p.name, p.id] } %>
    
      ...
    
    <% end %>
    

    在这种情况下,不需要accepts_nested_attributes_for :gift,因为您是从可用的列表中选择礼物,而不是在捐赠者表单中创建它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      相关资源
      最近更新 更多