【问题标题】:How to save attributes using Form Objects in Rails如何在 Rails 中使用表单对象保存属性
【发布时间】:2014-12-23 22:01:54
【问题描述】:

我有一个包含 8-10 个属性的用户模型。 我尝试使用表单对象概念将验证内容提取到另一个 UserForm 类中。 仅供参考,我正在使用 Rails 4 :)

我的控制器:

class UsersController < ApplicationController
  def create 
    @user = UserForm.new(user_params)
    @user.save
  end

   def user_params
      # Granted permission for all 10 attributes. 
      params.require(:user).permit(:first_name, :last_name, :email....)
    end
end

我的自定义类如下所示:

class UserForm < ActiveModel::Validator
  # like this i have 10 attributes 
 attr_accessor  :first_name, :last_name, :email, ....
 #validation for all 10 attributes 


  def save
    if valid?
      persist!
      true
    else
      false
    end
  end

  private
    def persist!
      #I think this is a bad idea, putting all 10 attributes.
      #User.create(first_name: first_name, email: email, .... )
      # what better solution we can have here ? 
    end

end

到目前为止,一切似乎都很好。只是我很困惑如何使用 User.create 直接保存所有属性(在persist!方法中)而不是手动分配每个值?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activemodel


    【解决方案1】:

    UserFrom.create(user_params)

    另外,为什么不只是 User.create(user_params) ?

    【讨论】:

    • “另外,为什么不只是 User.create(user_params) ?”如果我这样做,那么拥有一个单独的 UserForm 类有什么意义呢在一个单独的类中的东西。顺便说一句,UserForm.create(user_params) 不起作用,因为 UserForm 没有任何 create 方法。
    【解决方案2】:

    您是否研究过“Virtus”宝石。它使处理 Form 对象变得非常容易。 https://github.com/solnic/virtus

    class UserForm < ActiveModel::Validator
    
    include Virtus.model
     attr_accessor  :user
    
    
     attribute :first_name, String
     attribute :last_name, String
     attribute :email, String
     and so on..
    
      def save
        if valid?
          persist!
          true
        else
          false
        end
      end
    
      private
        def persist!
           @user = User.create(self.attributes)
        end
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多