Rails 3 - Button_to路由到错误的控制器方法(:删除)

时间:2011-09-14 00:01:33

标签: ruby-on-rails routing

我遇到了button_to路由到错误的控制器删除问题。目标是在赋值控制器中调用delete方法并删除关系,但不删除Claim或Location。问题是它保持路由到位置控制器。

我有三种带有HMT设置的模型:

Claim
has_many :assignments
has_many :locations, :through => :assignments

Assignment 
belongs_to :claim
belongs_to :location

Location 
has_many :assignments
has_many :claims, :through => :assignments

在索赔控制器中,我有以下声明来获取索赔的所有位置。

@locations = @claim.locations.all

在声明视图中,我有以下声明

<% @locations.each do |location| %>
...
<td><%= button_to 'Remove', location , :method => :delete %></td>
<% end %>

因此,当我选择按钮时,它会调用Locations控制器中的delete方法。 我需要将其设置为在赋值控制器中调用delete方法,赋值控制器是声明和位置之间的链接。

  1. 我试图改变数据的方式@locations = @ claim.locations.all也可以使用:include,或:join来读取赋值信息,但似乎没有任何东西将它添加到返回的数据中。

  2. 我试图更改button_to来调用作业,但我不知道怎么做。

2 个答案:

答案 0 :(得分:0)

您可以迭代分配而不是位置:

@assignments = @claim.assignments.include(:locations).all

在您的视图中,您可以显示位置信息:

<%= @assignments.each do |a| %>
    <h3><%= a.location.name %></h3>
    ...etc
    <%= button_to 'Remove', a , :method => :delete %>
<% end %>

答案 1 :(得分:0)

您最好的选择是添加其他操作并路由到该操作。所以在你的config/routes.rb文件中添加如下内容:

match 'location/remove' => 'location#remove', :via => [:delete]

然后在controllers/location_controller.rb放置:

def remove
  # You'll have to pass the current claim.id in via the form
  my_claim = Claims.find(params[:claim_id])
  @location.claims.delete(my_claim)
end

实际上没有尝试过这个,但它应该以最小的努力工作。

Credit for the delete trick

相关问题