1

我有一个我想属于用户的帖子模型。当我这样做时,我无法在视图中引用任何用户的东西。我正在使用设计。

帖子模型:

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

4

1 回答 1

1

谢谢大家,我修好了。这是我的创建动作。我计划重构它以使用工厂模式。

@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
于 2012-12-28T16:25:14.887 回答