I've read through the relevant Stack questions but still seem to be hitting a routing error with the following code:
Routes.rb
resources :memberships do
put :toggleon
put :toggleoff
end
Memberships_controller.rb
def toggleon
@membership = Membership.find(params[:id])
@membership.update_attributes(:active => true)
if user.id == membership_id
redirect_to root_path
else
redirect_to group
end
end
def toggleoff
@membership = Membership.find(params[:id])
@membership.update_attributes(:active => false)
if user.id == membership_id
redirect_to root_path
else
redirect_to group
end
end
Show.html.erb
<% if this_membership.active %>
<%= link_to 'Pause', this_membership, controller: :memberships, method: :toggleoff, style: 'color:#ccc' %>
<% else %>
<%= link_to 'Start', this_membership, controller: :memberships, method: :toggleon, style: 'color:green' %>
<% end %>
Error text
Started POST "/memberships/13" for 127.0.0.1 at 2011-09-27 23:35:35 +0100
ActionController::RoutingError (No route matches "/memberships/13"):
I can destroy memberships just fine but toggling the membership activity is proving tricky.
Thanks in advance!
Second attempt
<%= link_to("Pause", membership_toggle(@membership), :method => :put, :title => "This toggles it off") %>
<% else %>
<%= link_to("Toggle On", membership_toggle(@membership), :method => :put, :title => "This toggles it on") %>
and
def toggle
@membership = Membership.find(params[:id])
@membership.toggle!(active)
end
and
resources :memberships do
member do
put :toggle
end
end
now gives me this error...
undefined method `membership_toggle' for #<#<Class:0x00000102e69bc0>:0x00000102e66ec0>开发者_开发问答;
Links using your routes are going to be:
link_to("Toggle On", membership_toggleon_url(membership), :method => :put, :title => "This toggles it on")
link_to("Toggle Off", membership_toggleoff_url(membership), :method => :put, :title => "This toggles it off")
You need to supply :method => :put
to the link_to method given that's what you have the route as in your routes file.
Something like this can be achieved with a single action:
resources :memberships do
member do
put :toggle
end
end
Then you can make use of a single boolean field in your controller by using the Rails toggle method.
This will let you do something like:
@membership.toggle(:on)
Try setting the route as being :on => :member
.
Also, there's an atomic toggle!
method that does what its name implies.
Kept having issues with various techniques but eventually found this article:
http://buckybits.blogspot.com/2011/09/simple-ajax-property-toggle-in-rails-30.html
BOOM!
精彩评论