2

我是 RoR 的新手。我的问题是关于更新关联的活动模型的属性。

class User
  has_many :toys
end

class Toy
  belongs_to :user
end

我有一个用户形式的页面,我可以在其中更新用户的属性,以及关联的 user_devices 的某些属性:

<%= f.text_field :age %> # from user
<%= f.text_field :email %> # from user
....
<%= f.check_box :is_new %> # from toy!!

当我使用 update_attributes() 发布表单并更新所有属性时,它显示“ActiveModel::MassAssignmentSecurity::Error”

@user.update_attributes(params[:user]) # it gives ActiveModel::MassAssignmentSecurity::Error

另一个问题是,我不知道如何命名玩具表中的“is_new”属性。它应该是:toys_is_new 吗?

我也希望更新相关玩具的属性。你能帮我解决这个问题吗?

4

2 回答 2

1

因为is_new?是来自Toy,你必须使用accepts_nested_attributes_for

#app/models/user.rb
class User < ActiveRecord::Base
  has_many :toys
  accepts_nested_attributes_for :toys
end

#app/controllers/users_controller.rb
class UsersController < ApplicationController
  def edit
    @user = User.find params[:id]
  end

  def update
    @user = User.find params[:id]
    @user.update user_params
  end

  private

  def user_params
    params.require(:user).permit(:age, :email, toys_attributes: [:is_new])
  end
end

要让它在 中工作view,您需要使用fields_for帮助器:

#app/views/users/edit.html.erb
<%= form_for @user do |f| %>
  <%= f.fields_for :toys, @user.toys do |t| %>
    <%= t.object.name %>
    <%= t.check_box :is_new %>
  <% end %>
  <%= f.submit %>
<% end %>
于 2016-02-06T10:53:54.967 回答
0

你必须使用强参数。它是在 Rails 4 中引入的。

例子:

您有一个User带有id, firstname, lastname,的模型email。用户应该只能更新名字和姓氏。

您的观点:

<%= form_for @user do |f| %>
  <%= f.text_field :firstname %>
  <%= f.text_field :lastname %>
  <%= f.submit %>
<% end %>

你的控制器:

before_action :set_user

def edit
end

def create
  if @user.update user_params
     # Set success message
     # redirect to proper site
  else
     # Set error
     render :edit
  end
end


private

def set_user
  @user = User.find(params[:id])    # Rescue against ActiveRecord::RecordNotFound error
end

def user_params
  params.require(:user).permit(:firstname, :lastname)   # Here the strong parameters stuff happens
end

如果您想允许更多参数,您只需将它们添加到permit方法调用中。

出于安全原因,您收到此错误。

您可以禁用强参数,config.action_controller.permit_all_parameters = true但我强烈建议您使用此功能。

于 2016-02-06T11:21:10.853 回答