我的 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
所以基本上 index 只是 show 的一个特殊版本,因此我希望它执行 show,呈现 show.html.erb View - 但我不想像 redirect_to 那样更改 URL .
我试过这种方法:
def index
now = Time.now.utc.strftime("%m%d")
params[:id] = now
show
render :action => "show"
end
现在,这有效,但它闻起来很难闻。
我是 Ruby 和 Rails 的新手,所以我想知道是否存在根本性错误或者是否有更好的方法来做到这一点?
最佳答案
你在那里做的似乎没问题。写得有点不同可能会稍微改善气味,但差异纯粹是装饰性的。
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
关于ruby-on-rails - 在不更改 URL 的情况下呈现另一个 Action?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4563537/