【问题标题】:Rails 3 - Button_to routing to wrong controller method (:delete)Rails 3 - Button_to 路由到错误的控制器方法(:delete)
【发布时间】:2011-09-14 00:01:32
【问题描述】:

我在将 button_to 路由到错误的控制器删除时遇到问题。目标是调用分配控制器中的删除方法并删除关系,但不删除声明或位置。问题是它一直路由到位置控制器。

我有三个带有 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 控制器中的删除方法。 我需要将其设置为调用分配控制器中的删除方法,该控制器是声明和位置之间的链接。

  1. 我尝试更改获取数据的方式@locations = @claim.locations.all 也可以使用 :include 或 :join 读取分配信息,但似乎没有将其添加到返回的数据中。

  2. 我已尝试更改 button_to 以调用分配,但我不知道如何。

【问题讨论】:

    标签: ruby-on-rails routing


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

      您最好的选择是添加另一个动作并为该动作添加路线。因此,在您的 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-18
        • 1970-01-01
        相关资源
        最近更新 更多