简体   繁体   English

Rails 4嵌套属性和强参数

[英]Rails 4 Nested Attributes and Strong Params

This is my first time messing with nested attributes. 这是我第一次弄乱嵌套属性。 I'm having an issue where I am trying to create a 'School' that has a 'Token' and its attributes. 我在尝试创建具有“令牌​​”及其属性的“学校”时遇到问题。 Upon submitting the form, I'll get errors saying 'The Token attributes cannot be blank' (b/c of my model validations) even though I am submitting the form with Token values for the Token attributes. 提交表单后,即使我提交的表单具有Token属性的Token值,我也会收到错误消息,“ Token属性不能为空”(模型验证的b / c)。

I think things are misaligned when looking at the server logs but I'm not sure why? 我认为在查看服务器日志时情况未对齐,但是我不确定为什么?

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"xbDhfXJotAfgg6O9rnrSuKy01cxoTi/ZpgaDuD4fkQA=", "school"=>{"name"=>"Palmer", "address"=>"123 Palmer lane", "city"=>"Baldwinsville", "state"=>"CA", "zip"=>"10001", "tokens_attributes"=>{"0"=>{"database"=>"Rhetorical studies", "start_date(1i)"=>"2013", "start_date(2i)"=>"8", "start_date(3i)"=>"29", "expiration_date(1i)"=>"2014", "expiration_date(2i)"=>"8", "expiration_date(3i)"=>"29"}}}, "commit"=>"Update"}

My schools model looks like this: 我的学校模型如下所示:

class School < ActiveRecord::Base
    has_many :users
    has_many :tokens
    accepts_nested_attributes_for :tokens
end

The schools_controller's new action looks like the following: school_controller的新动作如下所示:

  def new
    @school = School.new
    @school.tokens.build
  end

My Schools form has the following fields_for: 我的学校表格具有以下fields_for:

<%= f.fields_for :tokens do |builder| %>
  <p>
    <%= builder.label "Database(s)" %>
    <%= builder.text_field :database %>
  <p>
  <p>
    <%= builder.label "Start Date" %><br />
    <%= builder.date_select :start_date %>
  <p>
  <p>
    <%= builder.label "Expiration Date" %><br />
    <%= builder.date_select :expiration_date %>
  <p>
<hr />
<% end -%>

And the 'school_params' strong params in the 'schools_controller.rb' look like this: “ schools_controller.rb”中的“ school_params”强参数如下所示:

  def school_params
    params.require(:school).permit(:name, :address, :city, :state, :zip, tokens_attributes: [:id, :user_id, :school_id, :database, :start_date, :expiration_date])
  end

Based on the logs, it seems as though I'm doing something wrong in 'school_params'. 根据日志,似乎我在'school_params'中做错了什么。 Any thoughts? 有什么想法吗?

Oops. 哎呀。 I was working on this late last night. 我昨晚很晚在做这项工作。 In doing so I had '@school.tokens.build' in both the 'new' and the 'create' actions. 这样,我在“新建”和“创建”操作中都使用了“ @ school.tokens.build”。 Removed it from 'create', and it's working fine now. 从“创建”中删除了它,现在可以正常工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM