0

我的应用程序有一些问题,我有帖子,当我为帖子创建新回复时发布 has_many 回复,而不是添加到数据库'responce' post_id my routes.rb

resources :categories do
    resources :posts
  end

  resources :posts do
    resources :responces
  end

控制器

class ResponcesController < ApplicationController

    def new
        @post = Post.find(params[:post_id])
        @responce = @post.responces.new(post_id:params[:post_id])
    end

    def create
        @responce = current_user.responces.build(responce_params)
        @post = Post.find(params[:post_id])
    if @responce.save
      flash[:success] = "Вы откликнулись на задание"
      redirect_to post_path @post
    else
    render 'new'
  end
    end

    def show
    end

    private

    def responce_params
        params.require(:responce).permit(:price, :comment, :post_id)
    end
end

看法

<%= form_for([@post, @responce]) do |f| %>
<%= f.text_area :price %>
<%= f.submit "GO", class: "btn btn-large btn-primary" %>
<% end %>

但如果添加到视图中

<%= f.collection_select :post_id, Post.all, :id, :name %>

rails 创建 post_id 到数据库

帮助

4

2 回答 2

1

您正在以错误的方式做几件事。

第一:我认为您不需要为同一模型提供两个单独的资源。我建议像这样将所有三个资源相互嵌套。

resource :categories do 
  resource :posts do 
     resource :responces 
  end
end

这样您就可以在 params 哈希中找到所需的 category_id 和 post_id。

我还建议添加资源:shalow => true:categories使您的路线更漂亮。

第二:你需要params[:post_id]在你的创建动作中分配,像这样。

    @responce = current_user.responces.build(responce_params)
    @responce.post_id = params[:post_id]
    @post = @responce.post

或者,您可以像下面显示的那样在表单中添加一个隐藏字段,但我不喜欢这种方法,因为它可能导致安全风险。

<%= form_for([@post, @responce]) do |f| %>
  <%= f.text_area :price %>
  <%= f.hidden_field :post_id, :value => @post.id %>
  <%= f.submit "GO", class: "btn btn-large btn-primary" %>
<% end %> 
于 2013-11-14T17:28:05.817 回答
0

在您的表单中,您没有传入 post_id。你可能想要这样的东西:

<%= form_for([@post, @responce]) do |f| %>
<%= f.text_area :price %>
<%= f.hidden_field :post_id, :value => @post.id %>
<%= f.submit "GO", class: "btn btn-large btn-primary" %>
<% end %>

隐藏字段会将当前帖子的 id 作为 post_id 参数传递到您的表单中。

于 2013-11-14T17:22:20.643 回答