【问题标题】:Rails Form not saving Nested AttributesRails 表单不保存嵌套属性
【发布时间】:2014-12-05 03:49:04
【问题描述】:

我昨天问了一个类似的问题,但现在我有了更多信息。

我正在创建一个允许用户购买贺卡的商店(生日快乐、情人节)

我有两个模型:CardRecipient

class Card < ActiveRecord::Base

  belongs_to :recipient
  accepts_nested_attributes_for :recipient

  def valid_name
    if @recipient && @recipient.name.nil?
      @card.errors.full_messages.push("Name can't be blank")
    end
  end

  validate :valid_name
  validates_associated :recipient
  validates :recipient, presence: true
  validates :note, length: { in: 1..200 }

class Recipient < ActiveRecord::Base

  has_one :card

  validates :name, presence: true

end

卡控制器

def new
  @card = Card.new
  @card.build_recipient                                   
end

def create
  @card = Card.new(card_params)
  if @card.save
    flash[:notice] = "Your card was successfully added to your cart!"
    redirect_to :back
  else
    flash[:danger] = "Something was wrong"
    render 'new'
  end
end

参数

def card_params
  params.require(:card).permit(:note, :amount, :recipient_attributes:[:name, :email])
end

买卡表格

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

  <%= render 'shared/error_messages' %>

  <div class = "inner-form">

    <p>
      <div class = "heading">Card Details</br></div></br>
      <div class = "card">You can buy your cards here!</div></br>
      <small>To customize individual messages, add cards one at a time.</small></br>
    </p>

    <%= f.fields_for :recipient do |g| %>
      <strong>Name of Recipient:*</strong></br>
      <%= g.text_field :name %></br></br>
    <% end %>

    <strong>Note:</strong></br>
    <%= f.text_area :note %></br></br>

  </div>

<% end %>

当我填写表格时,我输入了一个注释,然后输入了收件人的姓名。我收到了这条消息

This form contains 1 error
Recipient can't be blank

然后我查看了我的开发日志,发现以下内容

Processing by CardsController#create as HTML
  Parameters: {"utf8"=>"√", "authenticity_token"=>"DxoxP01IV4GZSf+lXoB9bFO6kuHn0
IxdSUyneoAo8FI=", "card"=>{"recipient"=>{"name"=>"John", "email"=>"", "firs
tname"=>"", "lastname"=>"", "address"=>"", "city"=>"", "zipcode"=>""}, "delivery
_date"=>"", "message"=>"hi", "credit_card"=>{"card_number"=>"", "card_verificati
on"=>""}}, "style"=>"1", "amount"=>{"{:in=>1..20}"=>""}, "quantity"=>"1", "commi
t"=>"Add to Cart", "state"=>"1", "card_type"=>"1", "card_expires_on"=>"1"}
Unpermitted parameters: recipient, credit_card
   (0.0ms)  begin transaction
   (0.0ms)  rollback transaction
  Rendered shared/_error_messages.html.erb (0.0ms)
  Rendered cards/new.html.erb within layouts/application (24.0ms)
  Rendered layouts/_navigation.html.erb (4.0ms)
  Rendered layouts/_messages.html.erb (0.0ms)
Completed 200 OK in 192ms (Views: 176.0ms | ActiveRecord: 0.0ms)

根据日志传入了name参数John。但收件人值实际上是Hash,而不是String

它还说recipient 是一个不允许的参数,尽管我允许它。

我不想验证:recipient,只验证收件人姓名属性。

我什至尝试像上面那样创建自定义验证器并通过回调运行它。

我尝试的任何方法似乎都不起作用。

【问题讨论】:

    标签: ruby-on-rails ruby forms


    【解决方案1】:

    正如我从您的代码中看到的,您允许

    :recipient_attributes:[:name, :email]
    

    但参数包含

    "recipient"=>{"name"=>"John", "email"=>"", "firstname"=>"", "lastname"=>"", "address"=>"", "city"=>"", "zipcode"=>""}
    

    也许你应该先试试这个

    params.require(:card).permit(:note, :amount, recipient: [:name, :email])
    

    第二个问题,现在你在键前有冒号,表示参数数组

    第三,当当前模型包含 has_many 或 has_one 关系时,accept_nested_attributes 有效。但是你有belongs_to。 尝试交换这种关系。

    文档:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

    【讨论】:

    • 看起来这行得通。谢谢你。但现在我得到ActiveRecord::AssociationTypeMismatch in CardsController#create
    • 在这种情况下,我应该交换表格的顺序对吗?并将其作为form for @recipient 对吗?还有fields for :card?
    • 不,卡有_一个收件人。具有嵌套字段的基础对象应该有一个嵌套对象。所以形式保持不变。
    • 我以为是收信人有卡。一张卡片属于收件人。是不是反过来了?也许validates_associated 属于:recipient
    • 重新设计您的架构。更基础的模型应该嵌套相关模型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    相关资源
    最近更新 更多