How to handle mass assignment in this case

I have a user registration where the user sets his username, first_class and some other attributes. Now there are other attributes that I need to set, for example: str or: acc.

These attributes are likely to be set in a bulk assignment command, such as create. I would not want to do something like update_attribute on each of them separately. So I have to make them attr_accessible.

However, I do not want the user to install them. For example, if the user decides to have first_class = 'Ranger', I would set it: str, not him.

My idea is that I just save params [: first_class] or params [: username] and just explicitly set everything else in my create method for the user. So will you do it?

+3
source share
2 answers

I assume other attributes are predefined based on what the user selects as part of the registration process?

In this case, I would add a binding to your model before_createthat computes and assigns these attributes accordingly:

class PlayerCharacter < ActiveRecord::Base
  before_create :assign_attributes

  # ...

  # This is called after you call "update_attributes" but before 
  # the record is persisted in the database
  def assign_attributes

    # Stats are determined by the 'first_class' attribute
    stats = case first_class
      when "Ranger"  then { :str => 20, :dex => 19, :wis => 8 }
      when "Wizard"  then { :str => 10, :dex => 14, :wis => 18 }
    end

    self.attributes.merge!(stats)
  end
end
+6
source

Dan "PlayerClass" IMHO. , , . , , ui db.

:

+2

All Articles