Reputation: 653
I have a post model that I want to belong to user. When I did that, I couldn't reference any user things in the view. I'm using Devise.
The post model:
class Post < ActiveRecord::Base
attr_accessible :album, :artist, :song
belongs_to :user
validates_presence_of :album, :artist, :song
end
The User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable
# Setup accessible (or protected) attributes for your model
attr_accessible :username, :password, :password_confirmation, :remember_me
has_many :posts
validates_uniqueness_of :username
validates_presence_of :username, :password, :password_confirmation
end
And I tried to reference the username with <%= post.user.username %>
. I also tried <%= post.user%>
and <%= post.user.name %>
.
UPDATE: I added user_id
to the table. However, when I make a post, the username
and user_id
values don't get set.
Upvotes: 1
Views: 2309
Reputation: 653
Thanks everyone, I fixed it. here's my create action. I plan to refactor it to use the Factory pattern.
@post = Post.new(params[:post])
@post.username = current_user.username
@post.user_id = current_user.id
if @post.save
redirect_to action: "index"
@posts = Post.find(:all)
else
render action: 'new'
end
Upvotes: 1