您好我在使用Form Object重构模式. 我有两个模型,Project和User.这样的 Project.first.name # "Buy milk"User.first.name # "John Doe" 我有一个表单接受项目的名称和用户的名称. class UserForm include ActiveModel
我有两个模型,Project和User.这样的
Project.first.name # "Buy milk" User.first.name # "John Doe"
我有一个表单接受项目的名称和用户的名称.
class UserForm include ActiveModel::Model def initialize(name:'', project_name:'') @name = name @project_name = project_name end def persisted? false end def self.model_name ActiveModel::Name.new(self, nil, "ProjectForm") end delegate :name, :email, to: :user delegate :project_name, to: :project # PROBLEM: project has #name not #project_name method def user @user ||= User.new end def project @project ||= Project.new end end
主要问题在于代码的初始化和委托部分,因为Project和User都有一个字段名,因此我在初始化时不能同时使用@name.有没有办法做类似的事情
delegate name: :project_name?
谢谢!
你可以使用前缀class UserForm include ActiveModel::Model def initialize(name:'', project_name:'') @name = name @project_name = project_name end def persisted? false end def self.model_name ActiveModel::Name.new(self, nil, "ProjectForm") end delegate :name, :email, to: :user, prefix: true delegate :name, to: :project, prefix: true def user @user ||= User.new end def project @project ||= Project.new end end
更多信息:http://apidock.com/rails/Module/delegate
现在,您可以调用这样的前缀方法:
UserForm.new.user_name UserForm.new.project_name