我有一个由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直接保存所有属性(在持久化!方法)而不是手动分配每个值?
发布于 2014-12-24 13:37:04
UserFrom.create(user_params)
另外,为什么不直接使用User.create(user_params)呢?
发布于 2015-02-22 19:13:08
你有没有看过"Virtus“宝石。它使得处理表单对象变得非常容易。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
endhttps://stackoverflow.com/questions/27628650
复制相似问题