form_for路由错误[RoR]

时间:2013-12-21 03:03:16

标签: ruby-on-rails ruby

我在“topics_controller”中有一个名为“createpost”的方法,我试图从“topics_controller”中的show中访问,但我一直收到路由错误。

表格:

<%= form_for @community_post, :url => { :action => "createpost", :controller=> "community_topics" } do |f| %>

<%= render 'error_messages' %>

<%= f.label :text %>
<%= f.text_area :text %>

<%= hidden_field_tag :community_topic_id, @community_topic.id %>

<br>

<%= f.submit "Submit reply" %>

控制器行动:

  def createpost
    @community_post  = CommunityPost.new(community_post_params)

    @community_post.user_id = current_user.id   
    @community_post.community_topic_id = params[:community_topic_id]

    if @community_post.save
        redirect_to "/community_topics/#{@community_post.community_topic_id}", notice: 'Community post was successfully created.'
    else
        render action: 'new'
    end
  end 

我做错了什么,所以我可以纠正它?非常感谢。

2 个答案:

答案 0 :(得分:0)

你的路线应该有:

resources :comunity_topics do
  post 'createpost', action: 'createpost'
end

并且表单路径应该类似于:

createpost_comunity_topics_path

答案 1 :(得分:0)

将控制器中的方法createpost重命名为create,并在视图中删除form_for的url选项。或者,如果您真的想要使用createpost这样的动作,请定义路线:

resources :community_posts do
  collection do
    post :createpost
  end
end

但我怀疑你正在关注一些旧的教程,当时Rails的路由包含控制器的名称和要执行的动作。这种方法被放弃了,有利于RESTful路由。

在这里阅读当前的文档: http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default