我有一个我希望属于用户的帖子模型。当我这样做时,我无法在视图中引用任何用户的东西。我正在使用Devise。
帖子模型:
class Post < ActiveRecord::Base
attr_accessible :album, :artist, :song
belongs_to :user
validates_presence_of :album, :artist, :song
end
用户模型:
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
我尝试用<%= post.user.username %>
引用用户名。我还尝试了<%= post.user%>
和<%= post.user.name %>
。
更新:我在表格中添加了user_id
。但是,当我发帖时,username
和user_id
值未设置。
答案 0 :(得分:1)
谢谢大家,我修好了。 here's my create action。我计划重构它以使用工厂模式。
@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