我成功使用RJS在page.replace.html create.js.rjs上实现AJAX。我正在尝试更新两个位置而不是一个,并且在观看Ryan Bates Railscast之后我非常接近(我认为)但是我的/views/likes/create.js.rjs文件的语法有问题。情况如下:
位于/views/likes/create.js.rjs的是以下代码:
page.replace_html "votes_#{ @site.id }", :partial => @like
page.replace_html "counter", 10 - (@question.likes.count :conditions => {:user_id => current_user.id})
page[@like].visual_effect :highlight
我的问题在于第二行。 div“counter”在/views/question/show.html.erb页面中显示以下代码:
<div id="counter">
You have <%= 10 - (@question.likes.count :conditions => {:user_id => current_user.id}) %> votes remaining for this question
</div>
从观看屏幕投射后,我相信我的错误必须与第二行的语法有关。具体来说,他提到你不能使用本地实例变量,但不知道如何进行更改。想法?
更新:这是我得到的错误:
ActionView::TemplateError (undefined method `likes' for nil:NilClass) on line #2 of app/views/likes/create.js.rjs:
1: page.replace_html "votes_#{ @site.id }", :partial => @like
2: page.replace_html "counter", 10 - (@question.likes.count :conditions => {:user_id => current_user.id})
3: page[@like].visual_effect :highlight
app/views/likes/create.js.rjs:2:in `_run_rjs_app47views47likes47create46js46rjs'
app/views/likes/create.js.rjs:1:in `_run_rjs_app47views47likes47create46js46rjs'
app/controllers/likes_controller.rb:8:in `create'
Rendered rescues/_trace (103.8ms)
Rendered rescues/_request_and_response (0.4ms)
Rendering rescues/layout (internal_server_error)
更新:
class LikesController&lt; ApplicationController中
def create
@user = current_user
@site = Site.find(params[:site_id])
@like = @site.likes.create!(params[:like].merge(:user_id => @user.id))
respond_to do |format|
format.html { redirect_to @site}
format.js
end
end
end
更新:这是喜欢的形式:
<% remote_form_for [site, Like.new] do |f| %>
<%= f.hidden_field :site_name, :value => "#{site.name}" %>
<%= f.hidden_field :question_id, :value => @question.id %>
<%= f.hidden_field :ip_address, :value => "#{request.remote_ip}" %>
<%= f.hidden_field :like, :value => "1" %>
<%= submit_tag "^" , :class => 'voteup' %>
<% end %>
答案 0 :(得分:2)
尝试像这样获取@question,因为你的question_id将出现在params [:like] hash
中 @question = Question.find params[:like][:question_id]
无论如何要进行双重检查,请打印你的params,这样就可以在likes_controller的create action中添加一个puts语句。
puts params.inspect,params[:like][:question_id]
第2行你有这个错误(未定义的方法`喜欢'为nil:NilClass)
这意味着您的@question为零,您从未在创建操作中声明此实例。
希望这适合你。
答案 1 :(得分:0)
你得到@question = nil。你应该检查@question是nil还是@ question.likes.count = 0如果是这样你应该做(10-0)即
if //your condition here
page.replace_html "counter", "You have 10 votes remaining for this question"
else
page.replace_html "counter", 10 - (@question.likes.count :conditions => {:user_id => current_user.id})
OR
remaining_votes= (@question && !@question.likes.blank && @question.likes.count :conditions => {:user_id => current_user.id} !=0 )? @question.likes.count :conditions => {:user_id => current_user.id} : 0
page.replace_html "counter", "You have #{10-remaining_votes } votes remaining for this question"
答案 2 :(得分:0)
在控制器中,您需要加载@question
变量。