Using devise as my authentication system I would like to build my profile on user registration.

I read many topics about this on SO, and decided to take the approach of building the profile within the model:

profile.rb

class Profile < ActiveRecord::Base
  belongs_to :user

  attr_accessible :user_id, # FIXME This is secure?
end

user.rb

class User < ActiveRecord::Base

  devise ...

  has_one :profile
  accepts_nested_attributes_for :profile

  def build_profile
    Profile.create(:user_id => id)
  end

end

My two questions are:

Is having the user_id in attr_accessible dangerous (mass-assignement)?

Did I have to put my profile creation in a controller (registration create) using a transaction? (Here if my profile fails to build I have still a user record)

有帮助吗?

解决方案

Is having the user_id in attr_accessible dangerous (mass-assignement)?

yes it is, you should avoid adding foreign keys to attr_accessible most of the time, although there's scenario that it's ok to use (if the association publicly accessible like countries for example) or if you override the setter and do some kind of check..

Did I have to put my profile creation in a controller (registration create) using a transaction? (Here if my profile fails to build I have still a user record)

just add validates_associated :profile in User model and maybe also validates :profile, presence: true (kinda forgot if validates_associated allow nil or not)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top