Ruby-on-rails 从 params 哈希创建 Rails ActiveRecord 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5667075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:56:16  来源:igfitidea点击:

Creating Rails ActiveRecord model from params hash

ruby-on-railsactiverecord

提问by Kevin Pang

Most Rails tutorials show how to populate a model class via the params hash like so:

大多数 Rails 教程展示了如何通过 params 散列填充模型类,如下所示:

class UsersController < ApplicationController   
    def create
        @user = User.create(params[:user])

        # more logic for saving user / redirecting / etc.     
    end  
end

This works great if all the attributes in your model are supposed to be strings. However, what happens if some of the attributes are supposed to be ints or dates or some other type?

如果您的模型中的所有属性都应该是字符串,这将非常有效。但是,如果某些属性应该是整数或日期或其他类型,会发生什么情况?

For instance, let's say the User class looks like this

例如,假设 User 类看起来像这样

class User < ActiveRecord::Base
    attr_accessible :email, :employment_start_date, :gross_monthly_income
end

The :email attribute should be a string, the :employment_start_date attribute should be a date, and the :gross_monthly_income should be a decimal. In order for these attributes to be of the correct type, do I need to change my controller action to look something like this instead?

:email 属性应该是一个字符串,:employment_start_date 属性应该是一个日期,而 :gross_monthly_income 应该是一个小数。为了使这些属性具有正确的类型,我是否需要更改控制器操作以使其看起来像这样?

class UsersController < ApplicationController  
    def create
        @user = User.new
        @user.email = params[:user][:email]
        @user.employment_start_date = params[:user][:employment_start_date].convert_to_date
        @user.gross_monthly_income = params[:user][:gross_monthly_income].convert_to_decimal

        # more logic for saving user / redirecting / etc.
    end
end

采纳答案by Kevin Pang

According to the ActiveRecord documentation, the attributes should automatically be typecasted based on the column types in the database.

根据ActiveRecord 文档,属性应该根据数据库中的列类型自动进行类型转换。

回答by Mike Lewis

I would actually add a before_savecallback in your users model to make sure that the values you want are in the correct format i.e.:

我实际上会before_save在您的用户模型中添加一个回调,以确保您想要的值采用正确的格式,即:

class User < ActiveRecord::Base
  before_save :convert_values

  #...

  def convert_values
    gross_monthly_income = convert_to_decimal(gross_monthly_income)
    #and more conversions
  end

end

So you can just call User.new(params[:user])in your controller, which follows the motto "Keep your controllers skinny"

所以你可以调用User.new(params[:user])你的控制器,它遵循“保持你的控制器瘦”的座右铭