2014-03-06 74 views
0

不確定如何刪除'fly'和'invoice'之間的關聯關係。什麼到目前爲止,我已經試過從數據庫中刪除無法在導軌上刪除紅寶石中的HATBM關係

<table class="table table-condensed"> 
    <thead> 
    <tr> 
     <th>Invoice Flies</th> 
    </thead> 
    <tbody> 
     <% @invoice.flies.each do |fly| %> 
     <tr> 
      <td><%= fly.name %></td> 
      <td><%= link_to "delete", ??????, method: :delete, 
            data: { confirm: "You sure?" } %></td> 
     </tr> 
     <% end %> 
    </tbody> 
    </table> 

發票型號飛:

class Invoice < ActiveRecord::Base 
    attr_accessible :active 
    validates :user_id, presence: true 
    belongs_to :user 

    has_many :categorizations 
    has_many :flies, through: :categorizations 
end 

發票遷移:

class CreateInvoices < ActiveRecord::Migration 
    def change 
    create_table :invoices do |t| 
     t.boolean :active 
     t.integer :user_id 

     t.timestamps 
    end 
    add_index :invoices, :user_id 
    end 

end 

分類模型:

class Categorization < ActiveRecord::Base 
    attr_accessible :fly_id, :user_id 

    belongs_to :invoice 
    belongs_to :fly 
end 

分類mi格雷申:

class CreateCategorizations < ActiveRecord::Migration 
    def change 
    create_table :categorizations do |t| 
     t.integer :user_id 
     t.integer :fly_id 

     t.timestamps 

     add_index :categorizations, :user_id 
     add_index :categorizations, :fly_id 
    end 
    end 
end 

飛型號:

class Fly < ActiveRecord::Base 
    attr_accessible :description, :name 
    validates :description, :name, presence: true 

    has_many :categorizations 
    has_many :invoices, through: :categorizations 
end 

飛遷移:

class CreateFlies < ActiveRecord::Migration 
    def change 
    create_table :flies do |t| 
     t.string :name 
     t.string :description 

     t.timestamps 
    end 
    end 
end 
+0

我們需要的代碼模型'fly'和'invoice' – raviolicode

+0

現在我已經加入問題的模型。 – JRTurner1234

+0

jrturner1234發生了什麼事? '依賴:摧毀'沒有解決你遇到的問題? – raviolicode

回答

0

您可以使用dependent: :destroy這樣的:

class Fly 
    has_many :categorizations, dependent: :destroy 
    ... 
end 

這將破壞有關分類已那Fly

另外,記得使用Fly.destroy(:id)(不要使用Fly.delete(:id),否則它不會刪除依賴於Fly的分類已)