开发者

How to handle mass assignment in this case

I have a user registration where a user sets his username, first_class and some other attribs. Now,开发者_如何学Go there are also some other attributes that i have to set, like :str or :acc.

These attributes would probably be set in a mass assignment command like create. I would not want to do something like update_attribute on each one separately of course. Therefore, i have to make them attr_accessible.

However, i don't want the user to set them. For instance, if the user decides to have a first_class = 'Ranger', i would set his :str and and not him.

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


I'm guessing that the other attributes are pre-determined based on what the user selects as part of the registration process?

In that case, I'd add a before_create hook to your model that calculates and assigns those 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


Based on Dan's method, you could also just add a new "PlayerClass" model for your character IMHO. It can have a relationship that has a belongs_to to your player or character class so you can have many of those. That way if you need more classes you can add it via an admin control in your ui and add it directly to the db.

Just another take on it :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜