简体   繁体   English

如何将 Rails 3 视图限制为特定关系类别中的项目?

[英]How do I limit Rails 3 view to items in a specific relationship category?

I'm working on a classified listing style website and I'm pretty new to Rails... Hence this question.我正在一个分类列表样式的网站上工作,而且我对 Rails 还很陌生……因此出现了这个问题。

I have setup the listing data with scaffolds and have an MVC for my Posts, Categories, and Subcategories.我已经使用脚手架设置了列表数据,并为我的帖子、类别和子类别设置了 MVC。 I have the relationships working with belongs_to & has_many ... I've been able to find a way to list the subcategories that belong to each respective category with this code: <% if subcategory.category.id == category.id %> I'm not sure if this is the most efficient method for the views (ie with server & database requirements and all), but my real question is how to list only the posts that belong to a certain category & subcategory.我有与belongs_tohas_many的关系......我已经能够找到一种方法来使用以下代码列出属于每个类别的子类别: <% if subcategory.category.id == category.id %>我不确定这是否是最有效的视图方法(即服务器和数据库要求和所有),但我真正的问题是如何只列出属于某个类别和子类别的帖子。 Right now, the main view (reminiscent of the craigslist homepage) lists each category & subcategory and each links to the Subcategories index view.现在,主视图(让人想起 craigslist 主页)列出了每个类别和子类别以及每个指向子类别index视图的链接。 I have been unable to find a way to limit the view to just the category or subcategory that someone clicks to take them here.我一直无法找到一种方法来将视图限制为某人单击以将其带到此处的类别或子类别。

How would I go about doing that?我将如何 go 这样做?

Also, I want to setup the custom URL's based on the category/subcategory that a user clicks (eg domain.com/subcategory)... It seems best to mention that as it could come into play now with how to design this current functionality.另外,我想根据用户点击的类别/子类别(例如 domain.com/subcategory)设置自定义 URL... 最好提一下,因为它现在可以在如何设计当前功能方面发挥作用.

Any ideas/help would be greatly appreciated!任何想法/帮助将不胜感激! Thanks in advance!提前致谢!

Rails models have many powerful methods for various kinds of searches. Rails 模型有许多用于各种搜索的强大方法。

For example, if you have added例如,如果您添加了

has_many :subcategories

to your Category model, your list of subcategories of a certain category should be available via:对于您的Category model,您应该可以通过以下方式获得某个类别的子类别列表:

category.subcategories

Your best bet is to have a good read of the rails guides , particularly this one and this one .最好的办法是仔细阅读rails 指南,尤其是这一篇这一篇

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

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