开发者

Rails 3 - Button_to routing to wrong controller method (:delete)

开发者 https://www.devze.com 2023-04-04 12:16 出处:网络
I am having problems with the button_to routing to the wrong controller delete. The objective is to call the delete method in the assignment controller and delete the relationship, but not delete the

I am having problems with the button_to routing to the wrong controller delete. The objective is to call the delete method in the assignment controller and delete the relationship, but not delete the Claim, or Location. The problem is that it keeps routing to the location controller.

I have three models with a H开发者_JS百科MT setup:

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

Within the claims controller I have the following statement to get all of the location for a claim.

@locations = @claim.locations.all

Within a claims view I have the following statement

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

So when I select the button it calls the delete method within the Locations controller. I need to set it up to call the delete method within the assignment controller which is the link between the claims and the Locations.

  1. I have tried to change how I get the data @locations = @claim.locations.all to also read the assignment information using :include, or :join but nothing seems to add it to the data returned.

  2. I have tried to change the button_to to call the assignment but I do not know how.


You could maybe iterate over assignments, instead of locations:

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

In your view, you can display the location information:

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


Your best bet is to add another action and route to that action. So in your config/routes.rb file add something like:

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

Then in your controllers/location_controller.rb put:

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

Haven't actually tried this, but it should work with minimal effort.

Credit for the delete trick

0

精彩评论

暂无评论...
验证码 换一张
取 消