James Osborn
James Osborn

Reputation: 187

Rails 3: Associations with 3 combined models

I'm having trouble accessing a model through my associations. I have three models:

User.rb

class User < ActiveRecord::Base
 devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

 has_one :profile
 has_many :posts
 attr_accessible :email, :password, :password_confirmation, :remember_me
end 

Profile.rb

class Profile < ActiveRecord::Base
 belongs_to :user, :dependent => :destroy
 has_many :posts
 attr_accessible :currentlatitude, :currentlongitude, :forename, :surname, :profpicture, :notes                      
end

Post.rb

class Post < ActiveRecord::Base
 ...
 attr_accessible :title, :body, :tag_list, :blogger_id, :coverphoto, :locations_attributes
 belongs_to :user, :polymorphic => true
 has_and_belongs_to_many :locations
 has_one :profile
end

I want to display Profile.forename in the Posts index view next to my post title, however when I try;

<%= post.profile.forename %> 

I just get the following error:

SQLite3::SQLException: no such column: profiles.post_id: SELECT  "profiles".* FROM "profiles"  WHERE "profiles"."post_id" = 56 LIMIT 1 

I assume there is something wrong with the above associations, any idea what?

Upvotes: 0

Views: 345

Answers (2)

Thanh
Thanh

Reputation: 8624

I think you can do it by define association like this:

class Post < ActiveRecord::Base
  ...
  has_one :profile, :through => :user
end

Then, you can get: post.profile.forename

Hope this will help.

Upvotes: 0

Mark Huk
Mark Huk

Reputation: 2380

Try to keep your relations from both sides: belongs_to<=>has_many/has_one. So in your case you should change:

class Post < ActiveRecord::Base
 ...
 belongs_to :profile
 ...
end

Also for that to work, you should add profile_id to your posts table.

Upvotes: 1

Related Questions