我有一个我无法弄清楚的情景,
Profile Product
customer1 Iphone
customer2 Iphone
现在customer1出售他的iphone,所以我将不得不删除customer1和iphone之间的关联,但不删除个人资料或产品。我有一个名为product_profiles
的多对多关系的中间表,其中product_id
和profile_id
为字段。因此我需要从product_profiles表中删除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 %>
答案 0 :(得分:2)
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/
答案 1 :(得分:1)
您可以使用路径助手的第二个参数传递参数。
<%= 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?" %>
在您的控制器中,您可以访问params [:profile_id]