views:

39

answers:

3

I have a before_filter to set a arel relation, but then if I call first in the method it doesn't like it. It seems to work fine in the console. What am I missing here?

class TeamsController < ApplicationController
  before_filter :find_team

  def show
    @team.first
  end

  private

  def find_team
    @team = Team.where(:id => params[:id])
  end
end
A: 

There's an error, I don't know if it's a typo.

def TeamsController < ApplicationController

should be

class TeamsController < ApplicationController

About the issue, remember you can iterate tasks on a single record, not an array. In other words

@team = Team.where(:id => params[:id])

@team.first.tasks # => OK
@team.tasks # => Not OK, you're trying to call tasks on an Array
Simone Carletti
A: 

The where method returns a relation, not an object. To get an object, use the first method to return an object (or nil) from a relation.

def find_team
  @team = Team.where(:id => params[:id]).first
end

The first method does not update the relation - it returns an object when called on a relation.

Justice
So why does it not work if I call @team.first in the show method after the before_filter?
Cameron
Because, as I said, the `first` method does not update the relation - it returns an object when called on a relation. It *returns* an object. When you call `first` in your sample `show` method, you don't *do* anything with the returned `Team` object, and `@team` is still a relation, not a `Team` object.
Justice
A: 

You are throwing away the result of the call to first. You want to do something like:

  def show
     @team = @team.first
  end
DGM