2014-03-31 149 views
2

有兩種型號StudyMaterialCard如何在子級強參數中允許父級id屬性

class StudyMaterial < ActiveRecord::Base 
    has_many :cards, dependent: :destroy 
end 

class Card < ActiveRecord::Base 
    belongs_to :study_material 
end 

我設置了一個像這樣的強參數。

def card_params 
    params.require(:card).permit(:front, :back, :tips, :cardtype, :study_material_id) 
end 

當卡被創建時,我得到這樣的日誌。

Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxx", "card"=>{"front"=>"front", "back"=>"back"}, "commit"=>"Create Card", "study_material_id"=>"1"} 
    (0.3ms) begin transaction 
    SQL (1.5ms) INSERT INTO "cards" ("back", "created_at", "front", "updated_at") VALUES (?, ?, ?, ?) [["back", "back"], ["cardtype", ""], ["created_at", Mon, 31 Mar 2014 10:30:59 UTC +00:00], ["front", "front"], ["updated_at", Mon, 31 Mar 2014 10:30:59 UTC +00:00]] 
    (2.9ms) commit transaction 

它看起來像study_material_id未保存到數據庫。 我想這是關於強參數的,我該怎麼寫才能通過study_material_id

編輯[添加視圖和控制器]

這是views/study_materials/show.html.erb

<p id="notice"><%= notice %></p> 
<%= render 'cards/form' %> 

views/cards/_form.html.erb

<%= form_for([@study_material, @card]) do |f| %> 
    <% if @card.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@card.errors.count, "error") %> prohibited this card from being saved:</h2> 

     <ul> 
     <% @card.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :front %><br> 
    <%= f.text_area :front %> 
    </div> 
    <div class="field"> 
    <%= f.label :back %><br> 
    <%= f.text_area :back %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

而且controllers/study_materials_controller.rb

class StudyMaterialsController < ApplicationController 
    before_action :set_study_material, only: [:show, :edit, :update, :destroy] 

    # ... 
    def show 
    @card = @study_material.cards.build 
    end 
    # ... 
    private 
    def set_study_material 
     @study_material = StudyMaterial.find(params[:id]) 
    end 
end 
+2

''study_material_id'在形式'card'外面,提供'form.erb.html'或者形式請求。 –

+0

你在'params'中有'study_material_id'嗎? – Magnuss

+0

@Magnuss查看'log'。 –

回答

2

包括study_material_id表單裏面:

<%= form_for([@study_material, @card]) do |f| %> 
    <%= f.hidden_field :study_material_id, :value => @study_material.id %> 
    ... 

study_material_id這樣,應該裏面params[:card]定義,並通過對模型就這麼過去了。

相關問題