Reputation: 5693
I'm a newcomer to Ruby just using this forum to help understand the language while I code a sample application to hone my skills.
I've tried to set up a has many relationship between Product & Media. I suspect the challenge I"m having is because of the plural form medium, but not sure how to troubleshoot it.
class CreateMedia < ActiveRecord::Migration
def change
create_table :media do |t|
t.string :type
t.string :alt
t.boolean :is_primary
t.string :url_tiny
t.string :url_small
t.string :url_regular
t.string :url_large
t.string :title
t.timestamps
end
end
end
class Media < ActiveRecord::Base
attr_accessible :alt, :is_primary, :title, :type, :url_large, :url_regular, :url_small, :url_tiny
belongs_to :product
end
class Product < ActiveRecord::Base
attr_accessible :assoc_product,:product_id, :merch_associations, :aux_description, :buyable, :long_description, :name, :on_special, :part_number, :release_date, :short_description, :withdraw_date, :occasion
has_and_belongs_to_many :categories
has_many :merch_associations
has_many :assoc_products, :through => :merch_associations
has_many :media
...
When I run this (note dress_media is a populated Media object array):
products[i].media << dress_media[m]
I get this in the error console:
uninitialized constant Product::Medium
I looked in the DB and the table is indeed called Media, not medium. So I thought it should have been the plural right? (This code was generated from the rails generator)
Like I say I'm new to Rails so if someone can point me in the right direction to create this one to many between Product & Media, that would be great?
Upvotes: 2
Views: 3675
Reputation: 76
As I understand, you have a model called 'Media'. Note that 'Media', as you mention in your question, is already a plural. The correct would be having a model called 'Medium' and the following relationships:
class Medium < ActiveRecord::Base
attr_accessible :alt, :is_primary, :title, :type, :url_large, :url_regular,:url_small, :url_tiny
belongs_to :product
end
and
class Product < ActiveRecord::Base
attr_accessible :assoc_product,:product_id, :merch_associations, :aux_description, :buyable, :long_description, :name, :on_special, :part_number, :release_date, :short_description, :withdraw_date, :occasion
has_and_belongs_to_many :categories
has_many :merch_associations
has_many :assoc_products, :through => :merch_associations
has_many :media
...
end
At sometime you might want to set or overwrite Rails singularizations and pluralizations. I don't recommend doing it in that specific case, but take a look at http://blog.thefrontiergroup.com.au/2011/06/pluralizations-and-singularizations-inflections-in-rails-3/ just to know how to do it.
Note that if you create a model called 'Medium', the database table will be called 'Media'.
Upvotes: 6