I'm following the book Pragmatic Agile Web Development With Rails 4th Edition, BUT I'm using Rails 3.2.2 instead of 3.0.5 as recommended in the book:
~$ ruby -v
ruby 1.9.3p125 (2012-02-16) [i686-linux]
~$ rails -v
Rails 3.2.2
I got stuck when including AJAX to redraw the Cart without reloading the page. Here is the create action in line_items_controller.rb:
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to(store_url) }
format.js
format.json { render json: @line_item, status: :created, location: @line_item }
else
format.html { render action: "new" }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
And here is my RJS file create.js.rjs (under app/views/line_items):
page.alert('NO PROBLEM HERE')
page.replace_html('cart', render(@cart))
However, when I click the button that starts this action:
<%= button_to 'Add to Cart', line_items_path(:product_id => product), :remote => true %>
I get the following error in the development log:
ActionView::MissingTemplate (Missing template line_items/create, application/create with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :coffee]}. Searched in:
* "/home/me/src_rails/depot/app/views"
):
app/controllers/line_items_controller.rb:47:in `create'
If I change the filename of create.js.rjs to create.js.erb, the problem is corrected:
Rendered line_items/create.js.erb (0.4ms)
but nothing happens in the view.... not even the alert. What am I missing? What is the difference between file.js.erb and file.js.rjs?
It looks like rjs
has been removed as the default as of Rails 3.1. You could get it back by installing the prototype-rails
gem, but I think you should just use jQuery, which is the new default.
As for your code, the reason it's not working is that it's an rjs
template being interpreted as .js.erb
, and this is likely just producing invalid JavaScript (you should see errors in the JavaScript console in your browser). An rjs
template used to set the page
variable for you, and you would write Ruby code using it to manipulate your page. In a .js.erb
template, it works more like in your .html.erb
views. You write actual JavaScript, with Ruby embedded using <% %>
tags. So the code in create.js.erb
should look something like this:
alert('NO PROBLEM HERE');
$('#cart').html("<%= escape_javascript(render(@cart)) %>");
In rails >= 3.1 there is no jquery-rjs anymore. But you can use CoffeeScript here:
line_items/create.js.coffee
:
alert 'NO PROBLEM HERE'
$('#cart').html '<%= j render(@cart) %>'
or something like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With