简体   繁体   English

Ruby on Rails:作用域与辅助方法

[英]Ruby on Rails: Scope vs Helper Method

I'm pretty new to Rails and wanted to do something along the lines of choosing a subset of objects in my Model. 我是Rails的新手,想做一些事情来选择模型中的一部分对象。 For example, I have a Project model and wanted to select some subset of projects based on some join table with another model, Organizations. 例如,我有一个“项目”模型,并希望基于与另一个模型“组织”的联接表选择一些项目子集。

My initial thought was to create some helper method in projects_helper.rb that would perform the appropriate lookup on to determine which projects to return. 我最初的想法是在projects_helper.rb中创建一些辅助方法,该方法将执行适当的查找以确定要返回的项目。

Another thought was to utilize scoping as described here ( http://apidock.com/rails/ActiveRecord/Scoping/Named/ClassMethods/scope ). 另一个想法是使用此处所述的作用域( http://apidock.com/rails/ActiveRecord/Scoping/Named/ClassMethods/scope )。

Both seem to functionally complete the objective, but what would be the best practice way of accomplishing this? 两者似乎都在功能上实现了目标,但是实现这一目标的最佳实践方法是什么? Is there a key difference as to what can access each of these approaches? 关于什么可以使用这些方法,是否存在关键区别?

Thanks! 谢谢!

Depends on the point of view of the question being "asked" by the query. 取决于查询被“询问”的问题的观点。

If you are asking for an Organization's projects, you might choose the Org first, then display organization.projects. 如果您要查询组织的项目,则可以先选择组织,然后显示organization.projects。 Nothing fancy going on there beyond linking the models appropriately (organization has_many projects, project belongs_to organization) and having the organization_id as a foreign key in the projects table. 除了适当地链接模型(组织has_many个项目,project属植物到组织)并在项目表中将organization_id作为外键之外,没有什么比这更有意义的了。

I'm not sure if a named scope would be appropriate if the Organizations in your system are a dynamic quantity. 我不确定如果系统中的组织是动态数量,则命名范围是否合适。 You don't want to have a named scope for each if the list of organizations changes all that often. 如果组织列表经常更改,则您不想为每个名称都有一个命名范围。

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

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