0

我是 Rails 新手,正在尝试创建一个论坛。论坛有很多话题,话题属于一个论坛,有很多微博,微博既属于话题又属于用户。但是,无论我尝试什么,都不会创建帖子。目前,当我尝试发布时,我收到路由错误“没有路由匹配 [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

如您所见,我在创建函数中注释掉了第一行,因为我尝试根据微博与主题的关系进行发布,但无济于事。提前感谢,如果我发布更多代码,请告诉我是否有帮助!

4

1 回答 1

0

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

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

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

于 2013-07-31T07:00:47.733 回答