class Product < ActiveRecord::Basehas_many :line_itemsbefore_destroy :ensure_not_referenced_by_any_line_itemprivate# ensure that there are no line items referencing this productdef ensure_not_referenced_by_any_line_itemif line_items.empty?return trueelseerrors.add(:base, 'Line Items present')return falseendendend
This makes sense to me except of one part: if line_items.empty? I can only guess that line_items returns all the rows of the "line_items" table that contain the product.id of the currently instantiated Product object, is that right? But how does the model knows what to fetch just by "line_items"? Isn't that too little info that we give to our model, regarding the logic of the task it has to do? Don't we have to declare somewhere something like: return false if line_items.product.id == product.id ?
Thanks in advance people!
The fact that you have said has_many :line_items automatically makes a
method line_items available for any product that returns an array
(actually it is not strictly an array, but near enough) containing all
the line items for that product.
Similarly if you have a line item in @line_item then you can say
@line_item.product to get the associated product.
Have a look at the Rails Guide on ActiveRecord associations to find
all the methods that rails makes available.
Colin
rake db:seed
rake aborted!
/rails/depot/db/seeds.rb:55: syntax error, unexpected tLABELLineItem.create (product_id: 8, cart_id: 1)^
class CreateLineItems < ActiveRecord::Migration
def change
create_table :line_items do |t|
t.integer :product_id
t.integer :cart_id
t.timestamps
end
end
end
I see.Now I've upgraded my seeds.rb file, to add some entry into the line_items table and see how it works.Actually I've added this line: LineItem.create (product_id: '8', cart_id: '1')
but when I run rake db:seed I get this error:rake db:seed
rake aborted!
/rails/depot/db/seeds.rb:55: syntax error, unexpected tLABELLineItem.create (product_id: 8, cart_id: 1)