开发者

create.js.erb, destroy.js.erb: How do these files fit in a Rails app

开发者 https://www.devze.com 2023-01-17 01:36 出处:网络
I haven\'t been able to find documentation that talk about how开发者_StackOverflow社区 create.js.erb and destroy.js.erb fit in a Rails 3 app.

I haven't been able to find documentation that talk about how开发者_StackOverflow社区 create.js.erb and destroy.js.erb fit in a Rails 3 app.

What is the logic behind these types of Javascript files in the app > controllers? How and when are they accessed?


File extensions are associated with Mime types. Check my answer here. It was written for Rails 2.2.2, but the same logic still holds. Note that the respond_to syntax has changed in Rails 3.
Also, these files are not in app/controllers, but in app/views/<controller_name>/


When you access your action via XMLHttpRequest for example, your action will respond with a javascript file.

In your controller:

class MyController < ApplicationController

  respond_to :html, :js

  def show
    @my_model = MyModel.find(params[:id])

    respond_with @my_model
  end

end

The show action will respond with the html view when accessed via html, and with je js view when accessed via XMLHttpRequest.


Basicly those are the views rendered in respond to ajax call. When you do a normal request, then, then controller is passing the varaialbes to your view, ie. create.html.erb. If you do an Ajax call to the controller, then the controller is rendereing create.js.erb.

The main difference is, that in the create.html.erb you should have a full template of your page. In case of create.js.erb you should have a javascript code which can modify your views.

For example:

$('#comments-box').html("<%= escape_javascript(index_comments(@commentable, @comments)) %>");
$('#comments-box-spinner').hide();
$('#flash').html("<%= escape_javascript(render(:partial => 'layouts/flash', :collection => flash)) %>");
0

精彩评论

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

关注公众号