简体   繁体   中英

Rails call another controller's action

I have 2 models, Posts and Comments. I would like to create a button on the Post show view which directs it to Comment new action. So I create a new action in Post:

  def comment
    @post = Post.find(params[:id])

    redirect_to new_comment_path
  end

I want to save the post_id in the Comment models, so I create d hidden field in the new comment form:

  <div class="field">
    <%= f.hidden_field :post_id, :value => @post.id %>
    <%= f.label :body %><br />
    <%= f.text_field :body %>
  </div>

But error appeared: "Called id for nil".

I am very new, can anyone help? Or should I use other approach?

Well you are missing to pass the value, I had tried out this way and it works, for your example.

edited:

redirect_to :controller=>'comments', :action=>'new_comment', :post_id=>@post.id

receive as @post_id = params[:post_id]

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