如何在子强参数中允许父id属性

时间:2014-03-31 10:39:39

标签: ruby-on-rails ruby strong-parameters

有两种型号StudyMaterialCard

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

1 个答案:

答案 0 :(得分: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]内定义,然后传递给模型。