Rails 4 - 嵌套属性的问题

时间:2014-05-08 00:55:17

标签: ruby-on-rails ruby ruby-on-rails-4 nested-forms

我在表单中使用带有fields_for的嵌套模型时遇到了一些麻烦。具体来说,并非所有嵌套字段都保存。用户有很多经验,但是当我提交表单时,会在数据库中插入具有正确user_id但无内容的经验。

查看日志,我也收到错误:

unpermitted parameters: experience.
不幸的是,

Rails 4 nested attributes not saving没有帮助。

以下是代码:

SCHEMA

create_table "experiences", force: true do |t|
  t.string   "content",    null: false, default: ""
  t.integer  "user_id"
end

MODEL

#user.rb
class User < ActiveRecord::Base

  has_many :experiences
  accepts_nested_attributes_for :experiences


#experience.rb
class Experience < ActiveRecord::Base
  belongs_to :user
end

CONTROLLER

class UsersController < ApplicationController

def new
  @user = User.new
  @user.experiences.build
end

def update
  @user = current_user
  @user.experiences.build
  @user.update!(user_params)
  redirect_to root_path
end

def user_params
  params.require(:user).permit(:username, :email, :password, 
    :password_confirmation, :title, :blurb, :city, :state, 
    :style_list, :experience_attributes => [:id, :content])
end

查看

<%= form_for @user do |f| %>
  <!-- (Omitted) user fields -->
  <%= f.fields_for :experience do |experience_fields| %>
    <%= experience_fields.text_field :content, placeholder: 'Content' %>
  <% end %>
  <%= f.submit 'Edit profile' %>
<% end %>

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

这是你的问题:

@user.experiences.build # -> note "experience**s**"

这意味着当您使用fields_for时,您必须引用:experiences(您当前引用的是单数):

  <%= f.fields_for :experiences do |experience_fields| %>
    <%= experience_fields.text_field :content, placeholder: 'Content' %>
  <% end %>

这适用于您的strong_params

params.require(:user).permit(experiences_attributes: [:id, :content])