2015-07-25 3 views
1

Я работаю над программой, которая рассчитывает пайки. Каждый рацион имеет ration_items, состоящий из корма и количества.Идентификатор не сохраняется при отправке через collection_select во вложенной форме

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

Я хочу, чтобы пользователь мог добавить ration_items в рацион в представлении Рацион/редактирования. Вложенная форма выглядит следующим образом:

<%= 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 %>

Эта форма, однако, не сохранить feedstuff_id атрибут при использовании collection_select. (Он сохраняет атрибут feedstuff_id при отправке идентификатора через поле number_field, поэтому сильные параметры устанавливаются нормально). действия сервера при подаче нового ration_item как это:

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)

Взгляды этого, feedstuff_id в массиве с именем ration_item, в то время как другие атрибуты в массиве называется ration_items_attributes ? Я предполагаю, что мне нужно организовать это в действии редактирования rations_controller, но я просто не могу понять правильный путь. Любая помощь ценится!

ответ

0

Просто измените

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

в

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

К этому вы получите feedstuff_id в ration_items_attributes и вы можете сохранить feedstuff_id в DB без изменения кода контроллера.

+1

Да! Это решение. Спасибо за ваш очень быстрый ответ! – kees

+0

@kees Пожалуйста, отметьте мой ответ как принято :) – Pavan

Смежные вопросы