1

ユーザーに所属させたい投稿モデルがあります。私がそれをしたとき、ビューでユーザーのものを参照できませんでした。私は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値が設定されません。

4

1 に答える 1

1

みんなありがとう、私はそれを修正しました。これが私の作成アクションです。Factoryパターンを使用するようにリファクタリングする予定です。

@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 に答える