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?
Try to keep your relations from both sides:
belongs_to<=>has_many/has_one.So in your case you should change:
Also for that to work, you should add
profile_idto yourpoststable.