开发者

Rendering another Action without changing URL?

I have this code in my Rails 3 controller:

def index
    now = Time.now.utc.strftime("%m%d")
    redirect_to :action => "show", :id => now
end

def show
    begin
        @date = Time.parse("12#{params[:id]}") 
        dbdate = params[:id]
    rescue ArgumentError
        @date = Time.now.utc
        dbdate = @date.strftime("%m%d")
    end

    @date = @date.strftime("%B %d")
    @events = Event.events_for_date(dbdate)
end

So basically index is just a specialized version of show, hence I want it to execute show, render the show.html.erb view - but I do not want to change the URL like redirect_to does.

I have tried this approach:

def index
    now = Time.now.utc.str开发者_开发问答ftime("%m%d")
    params[:id] = now
    show
    render :action => "show"
end

Now, this works, but it just smells badly.

I'm new to Ruby and Rails, so I just wonder if there is something fundamentally wrong or if there is a better way to do this?


What you're doing there appears to be fine. Writing it a bit differently might improve the smell a bit, but the differences are purely cosmetic.

def index
  now = Time.now.utc.strftime("%m%d")
  params[:id] = now
  render_show
end

def show
  render_show
end

private

def render_show
  begin
    @date = Time.parse("12#{params[:id]}") 
    dbdate = params[:id]
  rescue ArgumentError
    @date = Time.now.utc
    dbdate = @date.strftime("%m%d")
  end
  @date = @date.strftime("%B %d")
  @events = Event.events_for_date(dbdate)
  render :action => 'show'
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜