【问题标题】:How to build a scope with a join in a Rails Model?如何使用 Rails 模型中的连接构建范围?
【发布时间】:2014-04-19 00:15:17
【问题描述】:

我想使用范围重新创建此 SQL 查询 @user1.attended_events.where('day < ? ', Date.new + 5)。

到目前为止,我知道我需要在UsersController 中设置@prev_events = @user.previous。

不幸的是,我不知道如何为User 模型编写previous 范围。我在下面给出了我最好的镜头:

这是用户模型:

class User < ActiveRecord::Base
..

    has_many :events, foreign_key: "creator_id" #instead of user_id, need to set own index

    has_many :event_relationships, foreign_key: "attendee_id"
    has_many :attended_events, through: :event_relationships, source: :attended_event
    has_secure_password

    ##How can I write this scope??
    scope :previous, joins(:event_relationships).where('attended_events.day < ? ', Date.new + 5)
..
end

我想在用户控制器中调用previous:

class UsersController < ApplicationController
..
  def show
   @user = User.find(params[:id])
   @prev_events = @user.previous
   @upcoming_events = @user.upcoming
  end
..
end

这里是Event模型供参考:

class Event < ActiveRecord::Base
    scope :past_events, -> { where('day < ? ', Date.new + 5) }
  scope :upcoming_events, -> { where('day >= ? ', Date.new + 5) }

  belongs_to :creator, class_name: "User"

  has_many :event_relationships, foreign_key: "attended_event_id"
  has_many :attendees, through: :event_relationships, source: :attendee
  validates :description, presence: true

end

【问题讨论】:

    标签: ruby-on-rails join scope


    【解决方案1】:

    在lambda 中使用查询方法:

    scope :previous, -> { joins(:event_relationships).where(
      'attended_events.day < ? ', Date.today + 5) 
    }
    

    我假设您希望从今天起 5 天后进行 Date.new + 5。

    【讨论】:

    • 我仍然收到一个错误:undefined method 'previous' 在Users#controller。有什么想法吗?另外,我正在学习教程,所以Date.new + 5 效果很好。
    • 啊,你称它为实例方法。请注意,范围实际上是类方法。现在有两种选择:1,将用户参数传递给此范围并使用User.previous_events(@user) 调用它,或者2,定义一个实例方法。其中哪一项满足您的要求?
    • 第二个……我想。具体来说,它希望我使用范围并调用“模型方法”:bit.ly/1hVnQbb
    • 无法使用实例调用模型范围。它们的行为类似于类方法。
    • 我意识到为模型方法创建范围可能不是最好的主意。相反,我将代码保留在模型User 类中的一个方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多