Update nested_attributes by default

2019-07-15 05:29发布

问题:

I try to update iproduction, a nested form from production and I have an error of params with this line : "wrong number of arguments (0 for 1)"

@production.update.iproductions_attributes(cow_id: @cow)

My create action production:

def create
    @production = @ranch.productions.create(production_params)
    @production.update(date: Date.today)
    @cows = @ranch.cows
    @cow = Cow.find_by(id: params[:id])
    @production.update.iproductions_attributes(cow_id: @cow)
    respond_to do |format|
      if @production.save
        format.html { redirect_to ranch_production_path(@production.ranch_id, @production), notice: 'Production was successfully created.' }
        format.json { render :show, status: :created, location: @production }
      else
        format.html { render :new }
        format.json { render json: @production.errors, status: :unprocessable_entity }
      end
    end
  end

Can you help me about the syntax ?

回答1:

It should be @production.iproductions.update_attributes(cow_id: @cow)

   def create
        @production = @ranch.productions.create(production_params)
        @production.update(date: Date.today)
        @cows = @ranch.cows
        @cow = Cow.find_by(id: params[:id])
        @production.iproductions.update_attributes(cow_id: @cow)
        respond_to do |format|
          if @production.save
            format.html { redirect_to ranch_production_path(@production.ranch_id, @production), notice: 'Production was successfully created.' }
            format.json { render :show, status: :created, location: @production }
          else
            format.html { render :new }
            format.json { render json: @production.errors, status: :unprocessable_entity }
          end
        end
      end