Rails, 如何删除 has_many 中的关联

Rails, How to delete an association in has_many through

我有一个想不通的场景,

Profile      Product
customer1    Iphone
customer2    Iphone

现在客户 1 出售他的 iphone,所以我必须删除客户 1 和 iphone 之间的关联,但不能删除个人资料或产品。我有一个中间 table 用于多对多关系称为 product_profilesproduct_idprofile_id 作为字段。因此我需要从 product_profiles table.

中删除 id

产品型号

has_many :product_profiles
has_many :profiles, :through => :product_profiles

个人资料模型

has_many :product_profiles
has_many :products, :through => :product_profiles

产品负责人

def destroy

    if ProductProfile.where(:product_id =>  params[:id]).where(:profile_id => ?).destroy //how to get the profile_id from view when clicked on delete button
      redirect_to admin_products_path
      flash[:success] = "Product Successfully Deleted!"
    else
      flash[:error] = "Sorry! Could not complete the request, please try again!"
      redirect_to :action => 'index'
   end  
 end

查看文件

<% @products.each do |b| %>
                <tr>
                    <td><%= @profile.name %></td> 

                    <td>
                    <% b.sub_categories.each do |p| %>
                        <%= p.name + ',' %>
                    <% end %>
                    </td>

                    <td><%= b.name %></td>
                    <td>
                    <%= link_to "<span class='glyphicon glyphicon-edit'></span>".html_safe,  edit_admin_product_path(b) %>
                   </td>
                   <td>
                    <%= link_to "<span class='glyphicon glyphicon-trash'></span>".html_safe, admin_product_path(b), :method => :delete, :title => "Delete Brand", "data-confirm" => "Do you really want to delete?" %>
                  </td>
                    </tr>
                <% end %>    

您可以使用路径助手的第二个参数传递参数。

<%= link_to "<span class='glyphicon glyphicon-trash'></span>".html_safe, admin_product_path(b, :profile_id => @profile.id), :method => :delete, :title => "Delete Brand", "data-confirm" => "Do you really want to delete?" %>

在您的控制器中,您将能够访问参数[:profile_id]

product = Product.find_by_id(product_id)
product.product_profiles.delete(product_profile_id)

删除不会破坏您的对象,只会破坏它们之间的关联。

来源: http://neyric.com/2007/07/08/how-to-delete-a-many-to-many-association-with-rails/