我是 Rails 的新手(我在 MVC 工作过,但不是那么多),我正在尝试以“正确”的方式做事,但我在这里有点困惑。
我有一个网站导航,可以根据不同的标准过滤项目,意思是:
Items.popular
Items.recommended
User.items
Brand.items # by the parent brand
Category.items # by a category
问题 是我不知道如何在 Controller 中处理这个问题,其中每个操作对每个项目集合执行类似的逻辑(例如,存储在 session 中并响应js)
或者我在 ItemsController
中为每个过滤器(大 Controller )设置了一个操作或者我把它放在 ItemsController
BrandsController
、CategoriesController
(重复逻辑),但两者都没有提供“干净”的 Controller 。
但我不知道女巫第一个更好,或者我是否应该做其他事情。
提前致谢!
最佳答案
您在问两个不同的问题。 Items.popular
和 Items.recommended
最好在您的 Item
模型中实现为 named scope这将 Xavier 推荐的内容抽象到模型中。然后在你的 ItemsController
中,你会有类似
def popular
@items = Item.popular
end
def recommended
@items = Item.recommended
end
这在功能上与 Xavier 推荐的没有区别,但对我来说,它更容易理解。 (我总是尝试为六个月后出现的我的版本编写代码,以免怀疑敲击键盘的人在想什么。)
您要问的第二件事是关于 nested resources 的.假设您的代码是这样的:
class User
has_many :items
end
然后您可以通过包含将用户路由到该用户的项目
resources :users do
resources :items
end
在你的 routes.rb 文件中。对其他嵌套资源重复上述操作。
你最后说的是
The problem is that I don't know how to deal with this in the controller, where each action does a similar logic for each collection of items (for example, store in session and respond to js)
如果我上面所说的不能为您解决这个问题(我认为它会解决,除非您遗漏了一部分。)这听起来像是子类化的情况。将公共(public)代码放在父类(super class)中,在子类中执行特定的操作并调用 super
。
关于ruby-on-rails - 在 Rails 中组织站点导航操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16857710/