使用link_to切换布尔值

时间:2011-09-27 22:42:22

标签: ruby-on-rails ruby-on-rails-3 link-to

我已阅读相关的Stack问题,但似乎仍然遇到以下代码的路由错误:

的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 %>

错误文本

Started POST "/memberships/13" for 127.0.0.1 at 2011-09-27 23:35:35 +0100

ActionController::RoutingError (No route matches "/memberships/13"):

我可以摧毁会员资格,但是开展会员活动是很棘手的。

提前致谢!

第二次尝试

                  <%= 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") %>

def toggle
   @membership = Membership.find(params[:id])
   @membership.toggle!(active)
end

resources :memberships do
   member do
      put :toggle
   end
end

现在给我这个错误......

undefined method `membership_toggle' for #<#<Class:0x00000102e69bc0>:0x00000102e66ec0>

3 个答案:

答案 0 :(得分:4)

使用您的路线的链接将是:

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")

你需要向link_to方法提供:method => :put,因为你的路线文件中有你的路线。

这样的事情可以通过一个动作来实现:

resources :memberships do
  member do
    put :toggle
  end
end

然后,您可以使用Rails toggle方法在控制器中使用单个布尔字段。

这将允许您执行以下操作:

@membership.toggle(:on)

答案 1 :(得分:2)

尝试将路线设为:on => :member

此外,还有一个原子toggle!方法,它的名字就是这样做的。

答案 2 :(得分:1)

保持各种技术的问题,但最终找到了这篇文章:

http://buckybits.blogspot.com/2011/09/simple-ajax-property-toggle-in-rails-30.html

BOOM!