【发布时间】: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