简体   繁体   English

控制器操作与实例方法决策 - Rails 4,设计

[英]Controller Action vs. Instance method decision - Rails 4, Design

Let's say I have a controller action which queries and updates attributes of a record:假设我有一个查询和更新记录属性的控制器操作:

def toggle_foo
  bar = Bar.find(params[:bar_id])
  bar.foo.nil? ? bar.update_attributes(foo: ...) : bar.update_attributes(foo: ...)
  render json: {...}
end

Should such (non-CRUD) actions call instance methods rather manipulating data directly?此类(非 CRUD)操作是否应该调用实例方法而不是直接操作数据?

I think your approach is OK.我认为你的方法是可以的。

What matters in MVC is making a clear separation of concerns. MVC 中重要的是明确分离关注点。 In this way, you're keeping query and decision operations in the controller, and delegate all of the data manipulation logic to the model.通过这种方式,您将查询和决策操作保留在控制器中,并将所有数据操作逻辑委托给模型。 This follows good practices in object orientation.这遵循了面向对象的良好实践。

You could just directly manipulate data on the controller, by, say, changing and saving data to the database there but that'd be a big maintenance no-no.您可以直接操作控制器上的数据,例如,更改数据并将其保存到那里的数据库中,但这将是一个很大的维护禁忌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM