我正在尝试在我的网站上创建一个AJAX星级评分表单。使用this site上的教程,我成功了。但是,每当我尝试向评级表单提交更新时,通过单击另一个单选按钮,对象的current_user评级值将返回N / A而不是正确的值。我已经按照教程去了T,我有点困惑为什么会发生这种情况。
有没有人在创建类似的东西时碰到这个?
以下是我的评级表代码:
<%
content_for(:scripts) do
javascript_include_tag 'public/rating_ballot'
end
%>
<%= form_for rating_ballot, remote: true, html: { class: "rating_ballot" } do |f| %>
<%= f.label "value_1", content_tag(:span, '1'), { class: 'rating', id: '1' } %>
<%= radio_button_tag("rating[value]", 1, current_user_rating == 1, class: 'rating_button') %>
<%= f.label "value_2", content_tag(:span, '2'), { class: 'rating', id: '2' } %>
<%= radio_button_tag "rating[value]", 2, current_user_rating == 2, class: 'rating_button' %>
<%= f.label "value_3", content_tag(:span, '3'), { class: 'rating', id: '3' } %>
<%= radio_button_tag "rating[value]", 3, current_user_rating == 3, class: 'rating_button' %>
<%= f.label "value_4", content_tag(:span, '4'), { class: 'rating', id: '4' } %>
<%= radio_button_tag "rating[value]", 4, current_user_rating == 4, class: 'rating_button' %>
<%= f.label "value_5", content_tag(:span, '5'), { class: 'rating', id: '5' } %>
<%= radio_button_tag "rating[value]", 5, current_user_rating == 5, class: 'rating_button' %>
<%= hidden_field_tag "game_id", @game.id %>
<%= f.submit :submit %>
<% end %>
这是我的 update.js.erb 文件:
$('#rating').replaceWith("<%= escape_javascript(render partial: 'games/ratings-test') %>");
以下是我的辅助方法:
def rating_ballot
if @rating = current_user.ratings.find_by_game_id(params[:id])
@rating
else
current_user.ratings.new
end
end
def current_user_rating
if @rating = current_user.ratings.find_by_game_id(params[:id])
@rating.value
else
"N/A"
end
end
以下是我在初次提交时点击第一个单选按钮时返回的示例。
<table id="rating">
<thead>
<tr>
<th colspan="2">Game Ratings</th>
</tr>
</thead>
<tbody><tr>
<td>Average Rating</td>
<td>1.0</td>
</tr>
<tr>
<td>Your Rating</td>
<td>N/A</td>
</tr>
</tbody>
</table>
以下是提交后页面刷新时的输出:
<table id="rating">
<thead>
<tr>
<th colspan="2">Game Ratings</th>
</tr>
</thead>
<tbody><tr>
<td>Average Rating</td>
<td>1.0</td>
</tr>
<tr>
<td>Your Rating</td>
<td>1</td>
</tr>
</tbody>
</table>
奇怪的是,在我刷新页面之前,Rails几乎没有在我的current_user上获取。
答案 0 :(得分:1)
好的,经过多次戳戳和刺激,我设法通过将“locals”参数放入update.js.erb文件中来实现这一点:
locals: {current_user_rating: params['rating']['value']}
我的新update.js.erb代码如下所示:
$('#rating').replaceWith("<%= escape_javascript(render partial: 'games/ratings-test', locals: {current_user_rating: params['rating']['value']}) %>");