Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在RubyonRails中,除了一个参数之外,有没有一种方法可以对所有东西使用mass赋值?_Ruby On Rails - Fatal编程技术网

Ruby on rails 在RubyonRails中,除了一个参数之外,有没有一种方法可以对所有东西使用mass赋值?

Ruby on rails 在RubyonRails中,除了一个参数之外,有没有一种方法可以对所有东西使用mass赋值?,ruby-on-rails,Ruby On Rails,我试图在我的应用程序中使用小写的params[:user][:email],但目前我正在使用@user=user.new(params[:user])(包括电子邮件)来创建def。除了单个项目外,是否允许对所有项目进行质量分配 我知道我不能使用批量分配,但我想知道这是否可行。你应该看看attr\u protected。这样,您就可以仅定义要防止体量指定的属性 是的 class User attr_protected :email end 以下是您如何使用它: user = User.new

我试图在我的应用程序中使用小写的
params[:user][:email]
,但目前我正在使用
@user=user.new(params[:user])
(包括电子邮件)来创建
def
。除了单个项目外,是否允许对所有项目进行质量分配


我知道我不能使用批量分配,但我想知道这是否可行。

你应该看看attr\u protected。这样,您就可以仅定义要防止体量指定的属性

是的

class User
  attr_protected :email
end
以下是您如何使用它:

user = User.new(params[:user])
user.email = params[:user][:email].downcase
但是,如果您想自动关闭email属性,只需覆盖
email=
方法,我强烈建议:

class User < ActiveRecord::Base
  def email=(other)
    write_attribute(:email, other.try(:downcase))                                                                                                                                                         
  end
end

Loading development environment (Rails 3.2.5)
irb(main):001:0> User.new({:email => 'Me@you.com'})
=> #<User id: nil, email: "me@you.com", username: nil, created_at: nil, updated_at: nil>
irb(main):002:0> User.new({:email => nil})
=> #<User id: nil, email: nil, username: nil, created_at: nil, updated_at: nil>
class用户User.new({:email=>'Me@you.com'})
=> #
irb(main):002:0>User.new({:email=>nil})
=> #