开发者

Rails 3.1: Calling a template via JavaScript

I was just going through this

old rails cast episode, and one thing it mentions is the (now obsolete, apparently) link_to_function code. One interesting snippet it mentions is

 link_to_function "Add a Task" do |page|
    page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new
  end

In short, clicking the "Add a Task" link appends the "task" partial to the page without ajax.

I'm familiar with how to do this in Rails 3/3.1 via AJAX and/or manual javascript, but how do y开发者_如何学运维ou pull in a template partial on the fly without touching ajax?


It just simply stores the html content within the javascript code, which it's rendered while the page is rendered. So when you click "Add a task" the partial is already there escaped in the javascript code of the add task action. Just take a look to the content of the page with firebug.

Also the docs shows that the instert_html looks like this for prototype:

def insert_html(position, id, *options_for_render)
  content = javascript_object_for(render(*options_for_render))
  record "Element.insert(\"#{id}\", { #{position.to_s.downcase}: #{content} });"
end

So you can see that the content is actually the task partial, and it's inserted into javascript code. Also i have to mention that this is an obtrusive way to use javascript.

Take a look at the docs.


I was going through the same railscast, and I figured out the reason why this is not working is because this method uses Prototype, which by default is unavailable with the Rails 3.1 .

You could get this working by installing prototype gem from:

https://github.com/rails/prototype-rails

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜