João Daniel
João Daniel

Reputation: 8986

How can I filter rows of a model by a certain value?

I want to return just the elements that belong to a user. The user_id value is a column from Run. What I want is to select just the runs that are from the current_user.

def index
  @runs = Run.all

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @runs }
  end
end

As tried something like

@runs = Run.where(user_id= => current_user.id)

But it didn't worked. How should I do it?

Upvotes: 0

Views: 335

Answers (3)

caulfield
caulfield

Reputation: 1373

Gem cancan is great for these purposes. If you add user_id condition for Run in Ability class with :read param, and load_resource in controller, gem automaticall load only needed runs for current user in index action. Read docs for addition :)

Upvotes: 1

Phrogz
Phrogz

Reputation: 303490

If you have an association between your User model and your Run model you should be able to do simply current_user.runs. For example:

class User < ActiveRecord::Base
  has_many :runs
end

class Run < ActiveRecord::Base
  belongs_to :user
end

I don't know your actual DB schema or model names, though, so I can't be sure if this is correct for your situation.

Upvotes: 5

Michael Berkowski
Michael Berkowski

Reputation: 270767

A parameterized .where() uses a syntax like:

@runs = Run.where("user_id = ?", current_user.id)

It can also be done as a hash, which may be a little more readable:

@runs = Run.where(:user_id => current_user.id)

Don't do it this way (as a plain string)...

as it potentially opens up SQL injection vulnerabilities, even though the id is unlikely to be tampered with...

# Don't do this...
@runs = Run.where("user_id = #{current_user.id}")

Review the documentation on ActiveRecord conditions for full details.

Upvotes: 2

Related Questions