我在Rails 3控制器中有这个代码:
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
所以基本上索引只是show的一个特殊版本,因此我希望它执行show,渲染show.html.erb视图 - 但我不想要像redirect_to一样更改URL
我尝试过这种方法:
def index
now = Time.now.utc.strftime("%m%d")
params[:id] = now
show
render :action => "show"
end
现在,这有效,但它只是闻起来很糟糕。
我是Ruby和Rails的新手,所以我只是想知道是否存在根本性错误,或者是否有更好的方法可以做到这一点?
答案 0 :(得分:4)
你在那里做的似乎很好。写一点点不同可能会改善气味,但差异纯粹是装饰性的。
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