user1560922
user1560922

Reputation: 267

Ruby on rails - Where SQL method

I want to get all the microposts where 'something' = true.

This code works fine

class UsersController < ApplicationController
  .
  .
  .
  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts
    @titre = @user.nom
  end
end

But when I tried to make a where sql method this code doesn't work.

class UsersController < ApplicationController
      .
      .
      .
      def show
        @user = User.find(params[:id])
        @microposts = @user.microposts.where("something = 'true'")
        @titre = @user.nom
      end
    end

any idea ?

Upvotes: 0

Views: 1244

Answers (2)

gabrielhilal
gabrielhilal

Reputation: 10769

  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.where(something: true)
    @titre = @user.nom
 end

See here or here for more info on narrowing the query scope.

Upvotes: 4

Michael
Michael

Reputation: 548

Write like this:

Micropost.where(user_id: params[:id], something: true)

Upvotes: 2

Related Questions