Ruby on rails 如何在Rails中使用表单对象保存属性
我有一个由8-10个属性组成的用户模型。 我尝试使用表单对象概念将验证内容提取到另一个UserForm类中。 仅供参考,我正在使用Rails 4:) 我的控制器:Ruby on rails 如何在Rails中使用表单对象保存属性,ruby-on-rails,ruby,ruby-on-rails-4,activemodel,Ruby On Rails,Ruby,Ruby On Rails 4,Activemodel,我有一个由8-10个属性组成的用户模型。 我尝试使用表单对象概念将验证内容提取到另一个UserForm类中。 仅供参考,我正在使用Rails 4:) 我的控制器: class UsersController < ApplicationController def create @user = UserForm.new(user_params) @user.save end def user_params # Granted permission
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 UsersController
我的自定义类如下所示:
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
classuserform
现在看来一切都很好。只是我不知道如何使用User.create(在persist!方法中)直接保存所有属性,而不是手动分配每个值 UserFrom.create(用户参数)
另外,为什么不仅仅是User.create(User_params)?您已经了解了“Virtus”gem。它使处理表单对象变得非常简单。
classuserform
“还有,为什么不仅仅是User.create(User_params)?”如果我这样做,那么有一个单独的UserForm类来提取验证并创建、保存相关内容有什么意义呢。。在模型中保留所有业务逻辑(与数据库相关),我试图在一个单独的类中获得基本的验证内容。顺便说一下,UserForm.create(user_参数)不起作用,因为UserForm没有任何create方法。
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