Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails接受嵌套的属性>;验证失败时丢失的生成_Ruby On Rails_Ruby_Ruby On Rails 3_Activerecord_Activemodel - Fatal编程技术网

Ruby on rails Rails接受嵌套的属性>;验证失败时丢失的生成

Ruby on rails Rails接受嵌套的属性>;验证失败时丢失的生成,ruby-on-rails,ruby,ruby-on-rails-3,activerecord,activemodel,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,Activemodel,当使用位置模型的接受嵌套属性保存到位置模型时发生验证时,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, :to

当使用位置模型的
接受嵌套属性
保存到
位置
模型时发生验证时,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

这是一个类似于这里的问题:


看第一个答案,这将有助于解决完全相同的问题:(如果你发布控制器代码,这将很容易解决。@soundar已经用控制器更新了我的帖子code@Elliot您使用了build_location,但没有在Sale Model中声明has_one:location您是否有
form.fields_for:items,@Sale.items.first do | item_fields |…
?我认为rails应该在验证错误?已使用控制器代码更新。是否认为已实现?
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