I'm very new to Rails, so maybe I'm just missing the "Rails way" of doing this, but I have a model, call it Post
. I can create a post from the canonical posts/new
page but also from another page, say home/index
.
In home/index
i have a form_for @post
(slightly different from the one in posts/new
, but say that i can use a partial). The problem is that in the PostController.create
I cannot pass the newly created @post object back to home/index
(in case of errors) because:
- if I don't specify a page to render, it will automatically render
posts/new
- i don't know the calling page in order to redirect it to the right calling page (
posts/new
orhome/index
) - even if i knew it (hacking the request referrer or using
redirect_to :back
), redirect_to doesn't pass objects back, so that @post is empty when called f开发者_如何学运维romhome/index
Any help? thanks
EDIT
Maybe a possible solution would be to get the calling controller / action from the request and render it back. Any way to do this?
In theory, you could achieve what you're trying to do by checking the referer:
def create
@post = Post.new
if @post.update_attributes(params[:post])
# redirect as appropriate
else
render :action => case request.referer
when new_post_path then "posts/new"
when "/" then "home/index" # assuming that home/index is the root of the site
end
end
end
To get the referrer page, you can make a hidden field with the name redirect
. You can use it in the controller.
redirect_to params[:redirect] || posts_path
Have you tried that you pass the post's id in the query string to the home/index
eg: /home/index?post_id=42
You can find out who called your page by looking at
request.referrer
I don't know if this is the "rails way" but here's my solution.
You can add a route for
match home/index/(:id) => "home#index"
and redirect to this after creating the Post
. Then in your Home
controllers index
action just do a
@Post = Post.find(params[:index]) if params[:index]
Your view should display the post if @Post
exists
I like this approach because it keeps all the logic where it should be. Routing logic in the controller and view logic in the views.
精彩评论