从(即将变得瘦)控制器转移到(不太胖)模型
我几乎不懂 Rails,更不用说 ruby,所以这可能是一个简单的问题。在我的控制器的一个显示操作中,我定义了一个变量来计算某些项目的总数,看起来像这样:
@total_of_items = SomeModel.where(:user_id => @user).sum(:amount)
这显然收集了该特定用户的所有金额属性并将它们相加。所以在我看来,我只需调用:
<%= @total_of_items %>
它就会出现。那么两个问题。首先,这真的是做这样的事情的最好方法吗?因为我可能想获取这个值并在另一个用户的视图中显示它以比较两者,或者类似的东西。似乎为了做到这一点,这必须是模型中的一种方法?我只是不确定。
我的第二个问题是如何获取控制器中定义的变量并将其放入模型中。这似乎是更“瘦控制器胖模型”的做事方式。帮助不大?
I barely understand rails, let alone ruby, so this is probably an easy one. In one of my controller's show action I have a variable that I have defined to calculate the total of some items, looks something like this:
@total_of_items = SomeModel.where(:user_id => @user).sum(:amount)
This obviously collects all of the amount attributes of this particular user and adds them up. So in my view I just call:
<%= @total_of_items %>
And it shows up. So two questions. First, is this really the best way to do something like this? Because I may want to take this value and show it in another user's view to compare the two, or something like that. It seems like in order to do that this would have to be a method in the model? I'm just not sure.
My second question is how to take a variable defined in the controller and put it in the model. It seems like that's the more "skinny controller fat model" way of doing things. Little help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是
范围
出现的地方。在你的模型中:然后在你的控制器中:
你甚至可以链接范围,这真的很棒。
http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html
This is where
scopes
appear. In your model:Then in your controller:
You can even chain scopes which is really great.
http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html
您可以通过创建一个范围(如 @apneadiving 演示)或通过封装查询的方法来简化控制器:
然后在您的控制器中:
在这种情况下,我将使用该方法,因为范围有点难以阅读。 Ryan Bates 在他的 Railscast 215 中记录了这一点:
您的情况非常简单,但我会考虑将逻辑放在类方法中。
You can simplify your controller by creating a scope (as @apneadiving demonstrates), or by a method that encapsulates the query:
then in your controller:
In this case I would use the method, because the scope is a little harder to read. Ryan Bates makes note of this in his Railscast 215:
Your case is pretty simple, but I'd consider placing the logic inside a class method.