【发布时间】:2013-11-17 07:52:05
【问题描述】:
我正在尝试在我的网站上创建 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。
【问题讨论】:
标签: jquery ruby-on-rails ajax forms ruby-on-rails-3.2