Search code examples
ruby-on-rails-4nested-formscollection-select

Id not saved when submitted through collection_select in nested form


I am working on a program that calculates rations. Each ration has ration_items, that consist of a feedstuff and a quantity.

class RationItem < ActiveRecord::Base
  belongs_to :feedstuff
  belongs_to :ration
  validates :name, presence: true
  
  def to_s
    name
  end
end

class Feedstuff < ActiveRecord::Base
  validates :user_id, presence: true
  validates :name, presence: true, length: {maximum: 20}, uniqueness: true
  belongs_to :user
  has_many :ration_items
  
  def to_s
    name
  end

    
end

class Ration < ActiveRecord::Base
  belongs_to :user
  has_many :ration_items, dependent: :destroy
  accepts_nested_attributes_for :ration_items
  validates :name, presence: true
  validates :user_id, presence: true
  
  def to_s
    name
  end
  
end

class RationsController < ApplicationController
  before_action :set_ration, only: [:show, :edit, :update, :destroy]

  # GET /rations
  # GET /rations.json
  def index
    @rations = Ration.all
  end

  # GET /rations/1
  # GET /rations/1.json
  def show  
  end

  # GET /rations/new
  def new
    @ration = Ration.new
  end

  # GET /rations/1/edit
  def edit
  end

  # POST /rations
  # POST /rations.json
  def create
    
    @ration = current_user.rations.build(ration_params)
    
    respond_to do |format|
      if @ration.save
        format.html { redirect_to @ration, notice: 'Ration was successfully created.' }
        format.json { render :show, status: :created, location: @ration }
      else
        format.html { render :new }
        format.json { render json: @ration.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /rations/1
  # PATCH/PUT /rations/1.json
  def update
    respond_to do |format|
      if @ration.update(ration_params)
        format.html { redirect_to @ration, notice: 'Ration was successfully updated.' }
        format.json { render :show, status: :ok, location: @ration }
      else
        format.html { render :edit }
        format.json { render json: @ration.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /rations/1
  # DELETE /rations/1.json
  def destroy
    @ration.destroy
    respond_to do |format|
      format.html { redirect_to rations_url, notice: 'Ration was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_ration
      @ration = Ration.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def ration_params
      params.require(:ration).permit(:name, :user_id, ration_items_attributes: [ :id, :quantity, :name, :feedstuff_id ])
    end
end

I want the user to be able to add ration_items to a ration in the ration/edit view. The nested form looks like this:

<%= f.fields_for :ration_items, RationItem.new do |r| %>
    <%= r.label :quantity %>
    <%= r.number_field :quantity %><br>
    <%= r.label :name %>
    <%= r.text_field :name %><br>
    <%= r.label :feedstuff_id %>
    <%= collection_select(:ration_item, :feedstuff_id, Feedstuff.all, :id, :name, {prompt: 'Select Feedstuff'}) %>
  <% end %>

This form does however not save the feedstuff_id attribute when using the collection_select. (It does save the feedstuff_id attribute when submitting the id through a number_field, so strong params are set ok). Server action when submitting a new ration_item is like this:

Started PATCH "/rations/3" for 127.0.0.1 at 2015-07-25 11:30:01 +0200
Processing by RationsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"iH9Of4FEblYMcFz7Wu0dVp3yoIm58z30XrWX067PVNPc4N3FAFOg4yIUetz/7viuCCJf7a3REb7ief/qiM1dIQ==", "ration"=>{"name"=>"kalfjes", "ration_items_attributes"=>{"0"=>{"quantity"=>"100", "name"=>"krachtvoer"}}}, "ration_item"=>{"feedstuff_id"=>"15"}, "commit"=>"Ration bewaren", "id"=>"3"}
  Ration Load (0.1ms)  SELECT  "rations".* FROM "rations" WHERE "rations"."id" = ? LIMIT 1  [["id", 3]]
   (0.1ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "ration_items" ("quantity", "name", "ration_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["quantity", 100.0], ["name", "krachtvoer"], ["ration_id", 3], ["created_at", "2015-07-25 09:30:01.236937"], ["updated_at", "2015-07-25 09:30:01.236937"]]
   (210.8ms)  commit transaction
Redirected to http://localhost:3000/rations/3
Completed 302 Found in 226ms (ActiveRecord: 211.5ms)

By the looks of it, the feedstuff_id is in an array called ration_item, whereas the other attributes are in an array called ration_items_attributes? I presume I have to organise this in the rations_controller edit action, but I can just not figure out the correct way. Any help appreciated!


Solution

  • Just change

    <%= collection_select(:ration_item, :feedstuff_id, Feedstuff.all, :id, :name, {prompt: 'Select Feedstuff'}) %>
    

    to

    <%= r.collection_select(:feedstuff_id, Feedstuff.all, :id, :name, {prompt: 'Select Feedstuff'}) %>
    

    By that you will get feedstuff_id in ration_items_attributes and you can save feedstuff_id to DB without changing any of the controller code.