【问题标题】:Rails 4 - scopes - form of expressionRails 4 - 范围 - 表达形式
【发布时间】:2016-02-04 07:35:52
【问题描述】:

我正在尝试在 Rails 4 中制作应用程序。

我有用户、个人资料和项目的模型。

这些关联是:

User has_one :profile
Profile belongs_to :user & has_many :projects
Projects belongs_to :profile.

在我的个人资料显示页面中,我正在尝试显示属于该个人资料的项目。

我试图在我的项目模型中编写一个范围:

scope :by_profile, lambda { | profile_id | where(:profile_id => profile_id) }

然后,在我的个人资料显示页面中,我尝试将该范围用作:

<% Project.by_profile.sort_by(&:created_at).in_groups_of(3) do |group| %>
                        <div class="row">
                            <% group.compact.each do |project| %>
                            <div class="col-md-4">
                                <div class="indexdisplay">
                                    <%= image_tag project.hero_image_url, width: '80px', height: '80px' if project.hero_image.present? %>
                                    <br><span class="indexheading"> <%= link_to project.title, project %> </span>
                                </div>
                            </div>
                            <% end %>
                    <% end %>        
                        </div>

我是示波器的新手,但我仍在努力了解事物的工作原理。我有点惊讶的是,如果我将 'by_profile' 替换为 'all' 它确实显示了一系列项目(我认为每个项目,而不仅仅是那些由相关配置文件页面的配置文件 ID 创建的项目)。

有人知道如何写范围吗?我应该在配置文件控制器中做些什么来帮助完成这项工作吗?

【问题讨论】:

  • 为什么不使用Project.where(profile_id: 1)

标签: ruby-on-rails path scopes


【解决方案1】:

你在这里做什么

Project.by_profile..

无法正常工作,因为您已将范围 by_profile 定义为 1(它应该得到 proffile_id),但您没有传递任何内容。

Project.by_profile(params[:profile_id]).sort_by(&:created_at).in_groups_of(3) # will work

但在这里更简单的是使用关联:

Profile.find(params[:id]).projects.sort_by(&:created_at).in_groups_of(3)..

关于作用域你应该知道什么?它们几乎是“class”方法,但写得更好:)

当你调用一个作用域时,确保你传递了适量的参数给它。

这是定义范围的更短方法(-&gt; 称为 stubby lambda):

scope :by_profile, ->(profile_id) { where(profile_id: profile_id) }

【讨论】:

  • 嗨,Andrey,当我尝试这样做时,我收到一条错误消息:参数数量错误(0 代表 1)
  • @user2860931 你到底想做什么?
  • 你在文章末尾写的范围:scope :by_profile, ->(profile_id) { where(profile_id: profile_id) }
  • 你如何使用它?您是否将profile_id 传递给Project.by_profile(PROFILE_ID_HERE)
  • 我用原来的方法试过了,我也试过了:
猜你喜欢
  • 1970-01-01
  • 2016-07-11
  • 2016-08-23
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 2016-10-23
  • 1970-01-01
  • 2016-03-21
相关资源
最近更新 更多