many to many - Rails 4 - association not working correctly -
i created 2 models using rails generator this:
$ bin/rails g model manager name:string
and
$ bin/rails g model blog/post title:string manager:references
with that, have 2 models files:
# app/models/manager.rb class manager < activerecord::base has_many :blog_posts end
and
# app/models/blog/post.rb class blog::post < activerecord::base belongs_to :manager end
going rails console can create manager , post this:
$ manager1 = manager.new
$ manager1.name = "john doe"
$ manager1.save
$ post1 = blog::post.new
$ post1.title = "hello world"
$ post1.manager = manager1
$ post1.save
and on console, if do:
$ post1.manager.name
that works perfectly. returning manager's name. if do:
$ manager1.blog_posts
i expected list of manager's posts. getting error:
nameerror: uninitialized constant manager::blogpost
the same happing when try many-to-relationship between "blog:category (app/models/blog/category)" , "blog::post (app/models/blog/post.rb)"
update
@pavan solved first problem... , based in solution, tried this:
# app/models/blog/post.rb class blog::post < activerecord::base belongs_to :manager has_and_belongs_to_many :blog_categories, class_name: 'blog::category', foreign_key: 'blog_category_id' end
and:
# app/models/blog/category.rb class blog::category < activerecord::base has_and_belongs_to_many :blog_posts, class_name: 'blog::post', foreign_key: 'blog_post_id' end
and based on http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
, generate following migration:
class createblogcategoriesposts < activerecord::migration def change create_table :blog_categories_posts, id: false |t| t.belongs_to :blog_post, index: true t.belongs_to :blog_category, index: true end end end
but when try on console:
$ post1 = blog::post.first
$ post1.blog_categories
i got error:
2.2.2 :002 > p.blog_categories pg::undefinedcolumn: error: column blog_categories_posts.category_id not exist line 1: ...log_categories_posts" on "blog_categories"."id" = "blog_cate... ^ : select "blog_categories".* "blog_categories" inner join "blog_categories_posts" on "blog_categories"."id" = "blog_categories_posts"."category_id" "blog_categories_posts"."blog_category_id" = $1 activerecord::statementinvalid: pg::undefinedcolumn: error: column blog_categories_posts.category_id not exist line 1: ...log_categories_posts" on "blog_categories"."id" = "blog_cate... ^ : select "blog_categories".* "blog_categories" inner join "blog_categories_posts" on "blog_categories"."id" = "blog_categories_posts"."category_id" "blog_categories_posts"."blog_category_id" = $1
nameerror: uninitialized constant manager::blogpost
you have has_namy :blog_posts
defined in manager.rb
, rails classname
blogpost
isn't exist in case.
you should explicitly specify classname
tell rails use it.
# app/models/manager.rb class manager < activerecord::base has_many :blog_posts, class_name: 'blog::post' end
Comments
Post a Comment