如何按特定值过滤模型的行?

Joã*_*iel 0 ruby activerecord ruby-on-rails

我想只返回属于用户的元素.该user_id值是Run中的一列.我想要的只是选择runs来自的current_user.

def index
  @runs = Run.all

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @runs }
  end
end
Run Code Online (Sandbox Code Playgroud)

试过像

@runs = Run.where(user_id= => current_user.id)
Run Code Online (Sandbox Code Playgroud)

但它没有奏效.我该怎么办?

Phr*_*ogz 5

如果您的用户模型与运行模型之间存在关联,那么您应该能够做到这一点current_user.runs.例如:

class User < ActiveRecord::Base
  has_many :runs
end

class Run < ActiveRecord::Base
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

但是,我不知道您的实际数据库架构或型号名称,因此我无法确定这是否适合您的情况.