无法在主题页面的rails论坛中创建帖子

时间:2013-07-31 06:37:41

标签: ruby-on-rails routing forum posts

我是rails的新手,正在尝试创建一个论坛。论坛有很多主题,主题属于论坛,有很多微博,微博同时属于主题和用户。但是,无论我尝试什么,都不会创建帖子。目前,当我尝试发布时,我收到路由错误“No route matches [GET]”/ topics“”

我的routes.rb文件:

resources :users 
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
resources :forums, only: [:index, :show]
resources :topics, only: [:show]

_micropost_form.html.erb

<%= form_for(@micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
    <%= f.hidden_field :topic_id, value: @topic.id %>
    <%= f.hidden_field :user_id, value: current_user.id %>
    <%= f.text_field :summary, placeholder: "One-line summary..." %>
    <%= f.text_area :content, placeholder: "Compose a new post..." %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

microposts_controller.rb

class MicropostsController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy

def create
    #@topic = Topic.find_by_id(params[:topic_id])
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
        flash[:success] = "Your solution has been posted!"
        redirect_to topic_path(@topic)
    else
        redirect_to topic_path(@topic)
    end
end

def destroy
    @micropost.destroy
    redirect_to root_url
end

private

    def micropost_params
        params.require(:micropost).permit(:summary, :content, :user_id)
    end

    def correct_user
        @micropost = current_user.microposts.find_by(id: params[:id])
        redirect_to root_url if @micropost.nil?
    end
end

正如你所看到的,我在我的创建函数中注释掉了第一行,因为我已经尝试根据微博与该主题的关系进行发布,但无济于事。在此先感谢,如果我发布了更多代码,请告诉我它是否会有所帮助!

1 个答案:

答案 0 :(得分:0)

在您的:topics资源中,您没有定义索引方法,这就是您无法访问主题列表或索引页面的原因。尝试改变你的路线:

resources :topics, only: [:index, :show]

或仅从资源中删除属性,默认情况下它会自动包含所有方法。

resources :topics

此外,如果模型之间存在关系,则应在路径中定义嵌套路径 文件,例如,您可以像这样定义它们,您可以相应地更改它们:

尝试更改您的路线文件:

resources :users 
resources :sessions, only: [:new, :create, :destroy]

resources :forums do
  resources :topics do
    resources :microposts, only: [:new, :create, :destroy]  
  end
end

在上述情况下,您可以像这样访问您的论坛:

 http://localhost:3000/forums

您可以访问以下主题:

 http://localhost:3000/forums/id/topics

你可以像这样访问你的微博:

 http://localhost:3000/forums/id/topics/id/microposts

如果您想直接访问/microposts,则必须将其置于任何资源之外。

resources :microposts, only: [:index]    

现在您将能够访问它:

 http://localhost:3000/microposts

希望它会有所帮助。感谢。