0

我有两个模型用户和配置文件(用户来自设计)。一个用户可以有很多个人资料,所以我创建了一个迁移来将 user_id 添加到个人资料中。

class Profile < ActiveRecord::Base
belongs_to :user

attr_accessible :description, :name, :product, :image, :price , :user_id
mount_uploader :image, ImageUploader
validates_presence_of :name, :product,:image, :price
end

class User < ActiveRecord::Base

# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me

# attr_accessible :title, :body
has_many :profiles
validates_associated :profiles
end

在我的配置文件控制器中,我有一种创建新配置文件的新方法。我希望当用户登录时,他只能看到他的个人资料而不是全部。定义新

@profile = current_user.profiles.build

#@profile = @user.profile.new

respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @profile }
end

结尾

理想情况下,我的 user_id 列应该使用 build 进行更新,但我的 user_id 没有得到更新,这就是为什么不显示配置文件的原因。我正在使用带有 pg gem 的 postgresql,当我为该配置文件手动添加 user_id 时,我能够看到配置文件。

请帮助解决这个问题,我很长时间以来都能解决这个问题。如果您需要更多信息来解决这个问题,请告诉我。

4

1 回答 1

0

也许在你的控制器中尝试这样的事情:

if current_user.profiles.count == 0
  profile = Profile.create
  current_user.profiles << profile
end
于 2013-01-06T20:19:59.317 回答