我是 Rails 的新手,正在网上商店工作,只是为了编写一些 Rails。我有一个评论表单,需要一个隐藏字段来传递产品 ID。出于某种原因,我无法访问表单中的“产品”实例变量。
表格:
<%= form_for @comment, remote: true do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :comment %>
<%= f.text_area :comment %>
<%= f.label :rating %>
<%= f.text_field :rating, value: 5 %>
<%= f.hidden_field :product_id, :value => @product.id %>
<%= f.button :submit %>
<% end %>
我正在使用 new.js.erb 文件呈现表单:
$('#comment-form').html("<%= j (render 'layouts/review_form') %>");
$('#comment-form').slideDown(350);
这是触发链接和 div:
<%= link_to 'Write a review', new_comment_path, remote: true %>
<div id="comment-form" style="display:none;"></div>
当我摆脱 hidden_field 时,一切也都像预期的那样工作。有什么想法吗?
谢谢:)
最佳答案
在 Rails 中,实例变量只有在渲染该 View 的操作中定义时才在 View 中可用。例如,如果我们现在正在查看 comments/new.html.erb 文件,您需要在 comments_controller.rb 的“new”操作中同时定义@comment 和@product。所以现在,大概您的操作看起来像这样:
def new
@comment = Comment.new
end
现在要访问@product,您必须有一种方法来识别哪个产品是@product。我不知道您打算如何执行此操作,但如果我们将 product_id 想象成一个参数,这会起作用。
def new
@comment = Comment.new
@product = Product.find( params[:product_id] )
end
我不得不想象你还没有那个参数,但这基本上是必须在 Controller 中完成的。
一些场景中的另一个选项是使用@comment 和@product 之间的关系来访问 View 中的@comment.product.id,但这在这种情况下不起作用,因为您正在定义一个新的评论,其中可能还没有包含对产品的引用。
关于javascript - Rails - 无法访问表单中的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34634542/