【问题标题】:Mass assignment problem when instantiating a model实例化模型时的质量分配问题
【发布时间】:2011-07-29 16:37:39
【问题描述】:

我有一个用户模型(设计)并创建了一个具有 has_one / belongs_to 关系的 Profile 模型。我正在尝试在创建用户时自动创建配置文件,如下所示:

class User < ActiveRecord::Base   
   has_many :videos, :dependent => :destroy
   has_one :profile, :dependent => :destroy

    after_create :create_profile

  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

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

  protected

  def create_profile
    Profile.create :user_id => self.id
  end

end

已创建配置文件,但未填充用户 ID。我收到关于在个人资料上设置 :user_id 的批量分配警告,因为我有 attr_accessible 公开个人资料上的一些字段。

我不想删除 attr_accessible 但不明白为什么设置一个字段被视为批量分配。我认为这可能与传递哈希有关,因此我尝试了以下解决方法:

@profile = Profile.create
@profile.user_id = self.id

这会删除警告,但用户 ID 仍未在配置文件中设置。解决这个问题的正确方法是什么?

非常感谢任何清晰度! :)

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord mass-assignment


    【解决方案1】:

    您是否在解决方法结束时调用@profile.save?

    也许你可以试试这个:

    def create_profile
      self.build_profile.save
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多