New to rails here. My associations are setup as below, it might not be the ideal way so any recommendation is greatly welcomed:
User has many posts (posts table has user_id)
User has one profile (profile table has user_id)
Within my post controller view, I want to display the name of the profile (profile.name) that belongs to the user who owns the post.
My naive first guess was <%= @post.user.profile.name %> but that obviously didn’t work.
This is the association defined in my models:
class User < ActiveRecord::Base
has_many :posts
has_one :profile
end
class Post < ActiveRecord::Base
belongs_to :user
end
class Profile < ActiveRecord::Base
belongs_to :user
end
This is the code in the view: <%= @post.user.profile.name %>
The error is undefined method profile
you have to mention the following in your models
user.rb
profile.rb
post.rb
Then
<%= @post.user.profile.name %>should work.And if still there is a problem in your data