【问题标题】:Rails: updating joined Active Model's attributeRails:更新加入的 Active Model 的属性
【发布时间】:2016-02-06 10:16:42
【问题描述】:

我是 RoR 的新手。 我的问题是关于更新关联的 Active Model 的属性。

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 吗?

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

【问题讨论】:

标签: ruby-on-rails join activemodel associated-object


【解决方案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 %>

【讨论】:

  • 嗨@rich peck,感谢您的帮助。我传递了混乱更新错误,但另一个出现在这里:*** TypeError Exception: can't convert Symbol into String。它来自 user_params 方法;似乎解释器无法识别 :user 符号。
  • 哦该死的..我忘了说我使用的是rails 3.2.13!
【解决方案2】:

你必须使用Strong Parameters。它是在 Rails 4 中引入的。

例子:

您有一个模型 Useridfirstnamelastnameemail。用户应该只能更新名字和姓氏。

您的看法:

<%= 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 禁用强参数,但我强烈建议您使用此功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2018-09-03
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多