在我的 Rails 应用程序中,创建业务时我有一个包含以下字段的表单:
<%= check_box_tag(:default_company) %>
<%= label_tag(:default_company, "Set Company as Default") %>
基本上,当我创建一个企业时,如果他们选中此框,我需要它来运行类似以下代码的内容:
def set_default_company(company, user)
exists = DefaultCompany.find(user.id)
if exists
exists.update_attributes(company: company)
else
DefaultCompany.create(company: company, user: user)
end
end
在学习时,我通常会在我的 Controller 中做这些事情,但我正在尝试遵循最佳实践并使用胖模型、瘦 Controller ,所以我想使用这样的逻辑:
def create
@company = Company.new(params[:company])
if @company.save
if params[:default_company]
Company.set_default_company(@company.id, current_user.id,)
end
flash[:notice] = "Company was successfully created."
redirect_to @company
else
redirect_to new_company_path
end
end
这里是我对是使用类方法还是实例方法来调用 set_default_company
感到困惑的地方。它们看起来都行得通,但我看不出两者有什么好处。
除了提供有关使用哪种方法的任何信息外,如果有人可以向我展示将其编写为类方法与实例方法的简要实现,它可能会让我更好地理解原因。
我会这样写:
def self.set_default_company(company, user)
# Logic here
end
def set_default_company(company, user)
# Logic here
end
我认为以这种方式编写它们对任何一个都没有好处。
最佳答案
顾名思义,模型上的实例方法应该用于与用户的特定实例(调用该方法的实例)相关的逻辑/操作。因此您可以考虑为用户作为 User
上的实例方法。类方法适用于不对模型的单个实例进行操作的事物,或者适用于您没有可用实例的情况。例如您可能有一个类方法来整理您的数据库,例如 User.purge_expired_users
,它不适用于单个用户对象。
例如
class User
def set_default_company(company)
exists = DefaultCompany.find(self.id)
if exists
exists.update_attributes(company: company)
else
DefaultCompany.create(company: company, user: self)
end
end
end
那么您的 Controller 方法将如下所示:
def create
@company = Company.new(params[:company])
if @company.save
if params[:default_company]
current_user.set_default_company @company
end
flash[:notice] = "Company was successfully created."
redirect_to @company
else
redirect_to new_company_path
end
end
或者,您可以从另一个角度考虑这种关系,并在 Company
上放置一个实例方法,例如company.set_as_default_for(user)
。
关于ruby-on-rails - 我应该使用类方法还是实例方法,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11655593/