简体   繁体   中英

Rails ignoring render and redirect_to

I've got a really simple rails question here but I can't seem to find the answer anywhere. I guess some of the problems stem from me following a tutorial for Rails 1.2 with Rails 2.1. Anyway..

I'm writing a blog system and I'm implementing the comments bit. I have comments displaying fine once I've created them using script/console, but getting the comment form itself working is the hard bit.

In posts_controller.rb I have

  def comment
    Post.find(params[:id]).comments.create(params[:comment])
    flash[:notice] = "Added comment"
    #render :action => show
    redirect_to :action => show
  end  

and in show.html.erb (the view) I have

<%= form_tag :action => "comment", :id => @post %>
  <%= text_area "comment", "body" %><br>
  <%= submit_tag "Post Comment" %>

When I submit the form it tries to go to the urb /posts/comment/1 which is obviously incorrect, and it complains that it can't find a template. Obviously I don't want a template there because I've told it to redirect to the show action because I want it to just re-display the post's show page, with the new comment there.

I've tried both the commented out line (render :action => show) and the redirect_to line, and neither seem to do anything at all.

I'm sure I'm missing something simple, but what is it?

redirect_to :action => 'show', :id => params[:id]有show works周围的引号?

Rails 2.1 embraces "RESTful resources". show just happens to be the name of one of the predefined REST actions that all rails controllers use.

Rails does some magic behind the scenes, and :show is equivalent to "display this one specific element with a specific given ID". Sounds like it's getting mixed up with that. The ID is probably defaulting to "1". Hence the generated URL you're seeing from the render call

The Rails 2.1 way of doing it would use the following actions and templates:

  • index - displays the full list of comments
  • create - add a new comment
  • show - display a specific comment only (not the full list). Doesn't sound like this is what you want, but the "magic" inside rails will default to this.

There are also actions for new (show view to enter a new comment) edit (show view to do an edit of an existing comment) update (handle update submission) and destroy (duh), but it doesn't look like you'd use them in this example.

Do you have a link to the tutorial? Wouldn't be too hard to port it to Rails 2.1 style.

yes, you use old rails style.

Something new:

   form_for :comment, :url => { :post_id => @post } do |f|
     f.text_area :body
     submit_tag "Post"
   end

you can use resources for posts and comments, search google for better tutorial or install rails 1.2.6:

gem install -v 1.2.6 rails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM