将值设置为rails中的模型时出现问题

时间:2011-07-18 17:47:44

标签: ruby-on-rails-3 devise polymorphic-associations

我有一个名为User的模型。我正在使用Devise进行身份验证。 “用户”有许多“个人资料”和一个默认个人资料。所以我在User模型中添加了一个名为“default”的列。我想存储默认配置文件的ID。 但是,代码在current_user.default =语句中失败。

错误 - #User:0x402c480

的未定义方法`default ='
class User < ActiveRecord::Base

..........
has_many :profiles
...........

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :default

end

.......

class ProfilesController < ApplicationController

before_filter :authenticate_user! ,:except => [:show]



  def create
    @profile = current_user.profiles.new(params[:profile])
    @profile.user = current_user

    respond_to do |format|
      if @profile.save
      @current_user.default= @profile.id
       ............


end

我该如何解决这个问题?将“默认”添加到用户模型并不能解决问题。

1 个答案:

答案 0 :(得分:1)

我建议您使用STI,这意味着在“个人资料”表中添加“类型”列

class User < ActiveRecord::Base
  has_many :profiles
  has_one  :profile_default

  after_create do
    create_profile_default
  end
end

class Profile < ActiveRecord::Base
end

class ProfileDefault < Profile
end


def create
  @profile = current_user.profiles.new(params[:profile])
  @profile.user = current_user

  respond_to do |format|
    if @profile.save
    ...
end