简单表单无法路由更新和创建操作

时间:2019-09-06 05:12:44

标签: ruby-on-rails routing simple-form

背景用户故事:我有一个帖子集合,我想创建一个新帖子并更新现有帖子。

我创建了Post模型和Collection模型,并将它们彼此连接。我创建了所有html页面,以便用户可以访问帖子的集合,新的帖子表单,编辑帖子表单等。我能够访问html页面,因此我知道那里没有错。 问题是当我尝试提交表单时。创建新帖子后,当我单击“提交”按钮时,没有任何反应。我什至没有出错。编辑帖子后,当我单击“提交”时,出现“没有路线匹配[PATCH]”错误。所以我假设表单本身存在问题,或者创建和更新操作存在问题在职位控制器中。

我的帖子new.html.erb文件看起来像这样:

<h1>New Post</h1>

 <div class="row">
   <div class="col-md-8">
     <%= simple_form_for [@collection, @post], as: :post, url: collection_posts_path do |f| %>
       <%= f.label :body %>
       <%= f.text_area :body, rows: 8, class: 'form-control', placeholder: "Enter post body" %>
       <%= f.submit "Save", class: 'btn btn-success' %>
     <% end %>
   </div>
 </div>

我的帖子edit.html.erb文件如下:

<h1>Edit Post</h1>

 <div class="row">
   <div class="col-md-8">
     <%= simple_form_for @post, as: :post, url: edit_collection_post_path do |f| %>
       <%= f.label :body %>
       <%= f.text_area :body, rows: 8, class: 'form-control', placeholder: "Enter post body" %>
       <%= f.submit "Save", class: 'btn btn-success' %>
     <% end %>
   </div>
 </div>

我的routes.rb文件如下所示:

Rails.application.routes.draw do

  resources :collections do
     resources :posts, except: [:index]
  end

  resources :posts, only: [] do
     resources :comments, only: [:create, :destroy]
     resources :favorites, only: [:create, :destroy]
   end
end

我的posts_controller创建动作如下:

def create
    @collection = Collection.find(params[:collection_id])
    @post = @collection.posts.build(post_params)
        if @post.save
            flash[:notice] = "Post was saved."
            redirect_to [@collection, @post]
        else
            flash.now[:alert] = "There was an error saving the post. Please try again."
            render :new
        end
end

我的编辑和更新操作如下:

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

def update
  @post = Post.find(params[:id])
  @post.assign_attributes(post_params)

    if @post.save
      flash[:notice] = "Post was updated."
      redirect_to [@post.collection, @post]
    else
      flash.now[:alert] = "There was an error saving the post. Please try again."
      render :edit
    end
end

我的耙路看起来像this

0 个答案:

没有答案