Today I had a strange behavior that made me suspect of jQuery at first,
but then it happened that I've faced two gotchas, one from CoffeeScript
and one from Rails itself.
I have something like this:
routes.rb
post '/fields/:id.:format' => 'fields#show', as: :field,
constraints: {id: /\d+/}
post '/fields/remove/:id' => 'fields#remove', as: :remove_field
routes.js.coffee.erb:
<% h = Rails.application.routes.url_helpers
{ fields: false, remove_field: true }.each do |named_route, expect_id| %>
<% if expect_id %>
window.<%= named_route %>_path = (id, format='.json')-> "<%= h.send
:"#{named_route}_path", '999' %>#{format}".replace('999', id)
<% else %>
window.<%= named_route %>_path = '<%= h.send :"#{named_route}_path" %>'
<% end %>
<% end %>
It happens that my remove action is implemented like this:
def remove
Field[params[:id]].update deleted: true
head :ok
end
and in my client code I had something like this:
$.post remove_field_path(id, ''), => @refreshTree()
But as you have probably figured out the issue was that refreshTree was
never called.
That is because CoffeeScript will compare (format == null) and it
happens that ('' == null) in JavaScript:
https://github.com/jashkenas/coffee-script/issues/947
I've already fixed my routes.js.coffee.erb to something like:
path = (id, format)-> format = '.json' if format is undefined; ...
But then I realized that I was expecting Rails request to fail in the
first place since my original route was:
post '/fields/remove/:id'
instead of
post '/fields/remove/:id(.:format)'
Then, reading the guide on Routing, I've realized that the (.:format) is
not needed. I was confused because of the last example in the generated
routes.rb to restore the Rails 1 routes style:
# match ':controller(/:action(/:id))(.:format)'
Shouldn't this comment be changed to the example below to avoid such
confusion?
# match ':controller(/:action(/:id))'
Also, we could include some example like this to give a hint about the
default (.:format) rule:
# post '/products/remove/:id', format: false, as: :remove_product
Does it make sense?
Sorry for the long e-mail but I thought that a bit of context on a real
case might help understand how such examples in the routes.rb could help
others.
Cheers,
Rodrigo.
--
You received this message because you are subscribed to the Google Groups "Ruby on
Rails: Core" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-core?hl=en.