我有一个由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!方法中),而不是手动分配每个值?
答案 0 :(得分:0)
UserFrom.create(user_params)
另外,为什么不只是User.create(user_params)?
答案 1 :(得分:0)
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