我要尋找一個配方使用控制器的全局變量到這樣一個CoffeeScript的:Rails 3.1 - 在coffeescript中訪問控制器變量的最佳方式是什麼?
控制器:
respond_to :js
def create
@commentable = commentable
@comment = @commentable.comments.build({:comment => params[:comment], :user => current_user})
@comment.save
respond_with(@comment, @commentable)
end
create.js.coffee:
$("#form_#{@commentable.class}_#{@commentable.id}").hide()
的想法是在單個頁面中有幾個可評論的內容,並確定當前評論爲隱藏/顯示評論的表單;表單的ID是使用類和可評論的ID構建的。此時,如果我嘗試訪問上面的代碼的元素,它不起作用,因爲@commentable似乎不存在於腳本中。
編輯:
我讀答案here,我試過如下:
在我的職位/ show.haml
:javascript
var commentable_comments_id;
#post
@post.body
= render :partial => 'comments/list', :locals => {:commentable => @post}
在我的部分_list.haml
#comments_container
%div{:id => "comments_#{commentable.class}_#{commentable.id}"}
- commentable.comments.reverse_each do |comment|
= render :partial => 'comments/comment', :locals => {:comment => comment}
- if current_user
.add_comment_link{:id => "link_#{commentable.class}_#{commentable.id}"}
#{link_to "Commenter"}
.add_comment{:id => "form_#{commentable.class}_#{commentable.id}"}
= render :partial => 'comments/comment_form', :locals => {:commentable => commentable}
而在p artial _comment_form.haml
.comment_form
= form_tag polymorphic_path([commentable, Comment]) , :method => :post, :remote => true do |f|
.comment_field
= text_area_tag :comment, params[:comment], :id =>"comment_area", :rows => 4, :cols => 50
.comment_field
= submit_tag "Commenter", :id => "submit_comment_#{commentable.class}_#{commentable.id}", :class => "submit_comment"
在posts.js.coffee:
jQuery ->
commentable_link_id = null
commentable_form_id = null
hide_element_by_id = (id_name) ->
$("#"+id_name).hide()
show_element_by_id = (id_name) ->
$("#"+id_name).show()
$('.add_comment_link').click ->
currentId = $(this).attr('id')
if(commentable_link_id != null && commentable_form_id != null)
hide_element_by_id(commentable_form_id)
show_element_by_id(commentable_link_id)
commentable_link_id = currentId
commentable_form_id = currentId.replace("link", "form")
hide_element_by_id(commentable_link_id)
show_element_by_id(commentable_form_id)
commentable_comments_id = currentId.replace("link", "comments")
false
$('.submit_comment').click ->
if(commentable_link_id != null && commentable_form_id != null)
hide_element_by_id(commentable_form_id)
show_element_by_id(commentable_link_id)
因此,當鏈路上的用戶通過點擊添加評論,它隱藏在以前的評論的形式(如果有的話),它顯示了新的正確的一個,構建comments'container的標識(例如comments_Post_3),並將其存儲在頁面的全局變量JS:在create.js.coffee
commentable_comments_id = currentId.replace("link", "comments")
然後,我嘗試追加新的com彪在使用這個變量的存儲容器:
$('<%= escape_javascript(render(:partial => @comment))%>')
.appendTo("#"+commentable_comments_id)
.hide()
.fadeIn()
我認爲這是不正確的,因爲最後一次操作(與衰落追加)不工作,所以全局變量commentable_comments_id不能初始化或別的東西..
這很好,它的工作原理與我的預期完全一樣。只是一件事:上面的代碼在我的情況下不起作用,因爲要識別的id是'#form_Post_3'格式,所以我需要使用'$(「#form _ <%= @ commentable.class%> _ <%= @ commentable.id%>「)。hide()',沒有'#{}'。 – obo
我已使用更正更新了答案。 –
爲了使它在Heroku上工作,我需要在我的Gemfile中添加gem'therubyracer'。 – obo