开发者

Params hash in initialize method

I am new to RoR and building a new controller, I tried to get the :id from the params hash in the initialize method of the controller, but rails is coming back saying that it's a method... Everywhere I've read it's a hash so why the NoMethod error?

Anyway the main thing that has me stumped is why I can't access the params hash (or method or whatever it is :) ) from the initialize method?

开发者_运维问答

Really appreciate any help with this...

Thanks :)

class PeopleController < ApplicationController

  def initialize
    if params[:id] && !params[:id].empty
      @person = Person.find(params[:id])
    end 
  end

  def index
    @people = Person.all
  end

  def show
    @person = Person.find(params[:id])
  end

and a screenshot of the error is here: http://img820.imageshack.us/img820/6063/screenshot20110423at221.png

Thanks


Use a before_filter to get the result you are looking for:

class PeopleController < ApplicationController

  before_filter :find_person

  def index
    @people = Person.all
  end

  def show
    # @person is already set from the before_filter
    # @person = Person.find(params[:id])
  end

  private

  def find_person
    if params[:id] && !params[:id].blank?
      @person = Person.find(params[:id])
    end 
  end


Because initialize is called when the class is created. At this point, I imagine the request hasn't been processed yet. It might work better if you called super first, but I don't think Rails applications normally use the class initializer.


Try using a before_filter, might be more what you are looking for.


Example for my comment

def foo
  {:hello => "world", :foo => "bar"}
end

foo[:hello] # => "world"
foo[:foo]   # => "bar"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜