Reputation: 5
Hi I am working on creating a basic nest object structure in Rails and I am having some issues figuring out what direction to go in structuring things.
I want to have an object called Item related to an object called Product.
Here are the models:
class CreateItem < ActiveRecord::Migration
def change
create_table :items do |t|
t.integer :product_id
t.string :name
t.text :description
t.timestamps
end
end
end
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.text :description
t.decimal :price
t.string :image_file_name
t.integer :inventory
t.timestamps
end
end
end
Item always has 1 product associated with it and potentially the Product could have many referencing Items.
What I am having problems with is figuring out how to access these both within an html list easily. I know how to get access to the Item or the Product within a list, but I can figure out how to combine them within the same list and get the item.name and associated product.price in my html.erb.
Can anyone help or point me to a good example online of a similar structure in rails MVC where the model, controller and view have this all plugged in so I can see it?
Thanks in advance!
Upvotes: 0
Views: 151
Reputation: 15917
First, your your model definitions, you'll want to set up the one-to-many association.
class Product < ActiveRecord::Base
has_many :items
end
and
class Item < ActiveRecord::Base
belongs_to :product
end
Given you you have instance of Item
(i.e. a record from the database) stored in, let's call it, myitem
, you'll use the following to get the price
of the associated Product
.
myitem.product.price
Upvotes: 1