2014-03-31 61 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]定义,并通过对模型就这么过去了。

相关问题