开发者

Understanding Arel Better

I have a before_filter to set a arel relation, but then if I call first in the method it doesn't开发者_StackOverflow 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


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.


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

  def show
     @team = @team.first
  end


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜