我对rails非常陌生,我正在一家在线商店工作,只是想写一些rails。我有一个审查表格,需要一个隐藏的字段来传递产品标识。由于某些原因,我无法访问表单中的“product”实例变量。
表单:
<%= 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的时候,一切都像它所设想的那样工作。有什么想法吗?
谢谢:)
发布于 2016-01-06 13:56:48
在Rails中,只有在呈现视图的操作中定义了实例变量时,才能在视图中使用实例变量。例如,如果我们现在正在查看comments/new.html.erb文件,则需要在comments_控制员.‘s的“新”操作中同时定义@comment和@product。所以现在,大概你的行动看起来是这样的:
def new
@comment = Comment.new
end要现在访问“产品”,您必须有一种方法来识别哪个产品是“产品”。我不知道您打算如何做到这一点,但是如果我们假设product_id是一个参数,这将是可行的。
def new
@comment = Comment.new
@product = Product.find( params[:product_id] )
end我不得不设想,您还没有设置该参数,但这基本上是控制器中必须完成的工作。
在某些场景中,另一种选择是使用@comment和@product之间的关系来访问视图中的@comment.product.id,但是在这个场景中这是行不通的,因为您正在定义一个新的注释,它可能还没有包含对产品的引用。
发布于 2016-01-06 23:24:48
为了补充@ConnorCMcKee的答案,您需要使用嵌套资源而不是设置隐藏字段,我尽量避免隐藏字段(太容易操作)。
你会更擅长:
#config/routes.rb
resources :products do
resources :comments #-> url.com/products/:product_id/comments/new
end这将通过路由来设置params[:product_id]变量,而不是表单。它看上去可能不那么安全,但它提供了一个更有语义的吸引力:
<%= link_to 'Write a review', new_product_comment_path(@product), remote: true %>其他一切都应该按原样工作(使用@ConnorcMcKee's答案)
https://stackoverflow.com/questions/34634542
复制相似问题