【发布时间】:2014-08-28 14:09:44
【问题描述】:
我正在尝试为产品创建 cmets。不知何故,我无法将 text_field 中的值传递回 cmets 控制器。评论在数据库中创建,但表的正文列未填充。
我的产品模型是这样的 -
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 中显示 cmets -
<% @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 值传递回 cmets 控制器的地方。下面的代码和上面的代码都在 prodselect.html.erb 中。 prodselect 也是 Store 控制器中的一种方法 -
<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
我是 ror 的新手,所以任何指针都将不胜感激。我想知道为什么我无法将我的文本字段值传递给我的 cmets 控制器。我也尝试过使用 text_area 失败。
提前致谢
【问题讨论】:
-
您能发布您的完整表格吗?您的代码中有很多东西搞砸了
-
您可以发布
params来参与您的控制器操作吗?你可以在 Rails 服务器终端上找到它 -
嗨,这是在日志中传递的参数 - "comment"=>{"body"=>"Great Comment"} 。如何访问控制器中的值?
标签: ruby-on-rails ruby ruby-on-rails-4