【问题标题】:Rails accepts_nested_attributes > build being lost on validation failRails 接受_nested_attributes_for > 验证失败时构建丢失
【发布时间】:2012-04-02 05:45:08
【问题描述】:

如果在使用位置模型使用accepts_nested_attributes 保存到location 模型时发生验证,Rails 将在表单之前保存值时返回空白。

class Sale < ActiveRecord::Base
  belongs_to :location
  belongs_to :user
end

class Location < ActiveRecord::Base
  belongs_to :user
  has_many :sales
  validates_presence_of :street_address, :town, :state, :zip
end

class User < ActiveRecord::Base
  has_many :sales
  has_many :locations
end

当没有发生验证错误时,它会创建绝对正确的位置,但是当表单的任何部分发生验证错误时,位置字段的数据似乎丢失了。

有什么想法吗?

控制器代码

def new
    user = User.find(current_user.id)
    1.times { @sale.items.build; @sale.build_location; @sale.sale_times.build; }
  end

  def create
    @sale = Sale.new(params[:sale])
    respond_to do |format|
      if @sale.save
        format.html { redirect_to @sale, notice: 'Sale was successfully created.' }
        format.json { render json: @sale, status: :created, location: @sale }
      else
        format.html { 
          1.times { @sale.items.build; @sale.build_location;  }
          render action: "new" 
          }
        format.json { render json: @sale.errors, status: :unprocessable_entity }
      end
    end
  end

【问题讨论】:

  • 遇到完全相同的问题... :(
  • 贴控制器代码就很容易解决了。
  • @soundar 用控制器代码更新了我的帖子
  • @Elliot 您已使用 build_location 但您尚未在 Sale 模型中声明 has_one :location
  • 你有form.fields_for :items, @sale.items.first do |item_fields|... 吗?

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord activemodel


【解决方案1】:

这是一个与此处类似的问题:rails fields_for does not render after validation error on nested form

看看第一个答案,这应该会有所帮助

【讨论】:

  • 我认为 rails 是为了在验证错误时保留nested_attributes?
  • 已更新控制器代码。相信这已经实现了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
相关资源
最近更新 更多