2014-08-28 97 views
0

我正在尝试为产品创建注释。不知何故,我无法将text_field中的值传递回评论控制器。注释在数据库中创建,但表格的正文列未填充。无法将文本字段值传递给控制器​​4

我的产品型号是这样的 -

class Product < ActiveRecord::Base 
    has_many :comments 
    accepts_nested_attributes_for :comments 
end 

我的评论模式是这样的 -

class Comment < ActiveRecord::Base 
belongs_to :product 

end 

我的意见控制器看起来是如下 -

class CommentsController < ApplicationController 
def create 

@product = Product.find(params[:product_id]) 
@comment = @product.comments.build(body: params[:comment_body]) 
@comment.user_id = session[:user_id] 
@comment.product_id = params[:product_id] 
if @comment.save 

      redirect_to selection_path(params[:product_id]) 
     else 
      redirect_to selection_path(params[:product_id]), notice: "Please include a plain text comment only" 
     end 
     end 
     private 
     def comment_params 
     params.require(:comment).permit(comments_attributes: [ :body,:product_id ]) 
     end 
    end 

路线给出以下 -

get "store/prodselect/:id" => 'store#prodselect', as: :selection 
resources :products do 
get :who_bought, on: :member 
post "comments/create" => 'comments#create', as: :create_comment 
end 

我可以使用下面的代码,以显示prodselect.html.erb评论 -

<% @comments.each do |comment| %> 
<tr>   
<td class="tbody" style="width:150px;"><%= comment.uname %> 
    <%= image_tag @product.user.pic.url(:thumb), :width=>50, :height=>50 %> 
</td> 
    <td class="tbody" style="width:350px;"><%= comment.body %></td> 
</tr> 
<% end %> 

这是我无法通过text_field值回评论控制器的地方。以下代码和上面的代码位于prodselect.html.erb中。此外prodselect是在存储控制器的方法 -

<tr><td>      
<%= text_field :comment, :body%> 
<%= button_to 'Add comment' , product_create_comment_path(@product.id), :class => "buttonto" %> 
</td></tr> 

最后,在存储控制器我prodselect方法是这样的 -

def prodselect 
    @product = Product.find(params[:id]) 
    @comments = Comment.where(product_id: params[:id]) 
    @comment = Comment.new 
    end 

我是新来的回报率,因此任何指针将不胜感激。我想知道为什么我无法将我的文本字段值传递给我的评论控制器。我试过使用text_area也失败了。

由于提前

+0

你能发布你的完整表单吗?你的代码中有很多东西搞砸了 – Mandeep 2014-08-28 14:12:17

+0

你可以发布一些来自你的控制器动作的参数吗?你可以在rails服务器端找到它 – RAJ 2014-08-28 14:16:03

+0

嗨,这是在日志中传递的参数 - “comment”=> {“body”=>“Great Comment”}。我如何访问控制器中的值? – pari 2014-08-28 22:54:16

回答

0

button_to本身只是张贴到URL创建一个表单(我承认我已经解释说很差,去看看链接的文档),那么你的文本字段是不实际上是表格的一部分,因此没有通过。你将需要使用一个实际的形式

<tr> 
    <td> 
    <%= form_for [@product, Comment.new] do |f| %> 
     <%= f.text_field :body %> 
     <%= f.submit 'Add comment', :class => "buttonto" %> 
    <% end %> 
    </td> 
</tr> 
+0

嗨,我尝试在部分中使用form_for时收到错误消息。该消息是“Store#prodselect中的NoMethodError”。显示E:/demo/app/views/store/_form.html.erb其中第1行出现: 未定义的方法'product_comments_path'为#<#:0x4d1dc98> – pari 2014-08-28 22:26:06

+0

'<%= form_for [@product ,Comment.new],url:create_comment_product_path do | f | %>'我假设看看你的路线,如果不是耙路线,看看你的评论创建的路径是什么,并在url选项中使用它。 – 2014-08-29 08:05:03

0

你使用form_for或类似的东西?只有路径的button_to不会将信息发送到您的控制器。尝试阅读this

0

是的,我在路线中的路径不正确。也form_for帮助。谢谢你指点我正确的方向。

相关问题