Reputation: 876
On most tutorials out there, people tell you to create a js.erb
template for every action you want to respond with javascript
, which leads to having both an html.erb
and a js.erb
, for every action I want to work with AJAX, like this:
Is this right? Am I doing something wrong? Because it looks awful to me, there will be at least 20 files in each view folder, by default.
Upvotes: 0
Views: 72
Reputation: 3126
Yeah, it looks really awful to me too. But if you're responding to every method with javascript you'll have to create js.erb
templates for each them.
Another approach would be, you'd want to respond with json instead of script. Where all your ajax code will remain in the client side javascript, and you'll be responded back with json data.
For eg. lets get data for an particular area
$.ajax({
url: "/areas/23",
dataType: 'json',
method: 'get',
success: function(response){
//OPTION 1
//response will have all the data
//handle the value from the response object in displaying
//OPTION 2
//If you set dataType: 'html' you can receive html partial from server and make use of it directly
$("#show-area").html(response); //response will have content of _show.html.erb
},
error: function(error){
console.log(error); //Print errors if it breaks
}
});
#Controller
def show
respond_to do |format|
#OPTIONS 1
format.json { render json: @area.as_json }
#Or have a json.jbuilder partial if you want to send data selectively, ;) There is no escape from partials/templates
#OPTION 2
format.html { render partial: "areas/show" } # will render _show.html.erb
end
end
That being said, I think it finally comes to personal preference. And your preferences will vary upon different scenarios. You can pick any one of those based on the case. Let me know if it helped.
Upvotes: 1
Reputation: 21
I think you are doing right. You are using Rails’ AJAX helper and it is a good practice. Some advantages of this comparing to the normal way of using AJAX:
I don't know how complex your project is so I am not sure but maybe you can refine to have less partial files. For example, I noticed that you have both delete and destroy actions. Index, new and edit views may not need the partial files. It seems that you also handle Json requests. It also makes the view folder bigger.
Upvotes: 2