问题描述
|
我有一个用户注册,用户在其中设置他的用户名,first_class和其他一些属性。现在,还需要设置其他一些属性,例如:str或:acc。
这些属性可能会在大量分配命令(如create)中设置。我当然不想分别对每个对象执行类似update_attribute的操作。因此,我必须使它们attr_accessible。
但是,我不希望用户设置它们。例如,如果用户决定使用first_class = \'Ranger \',则我将设置他的:str而不是他。
我的想法是,我只保存params [:first_class]或params [:username],并在用户的create方法中显式设置其他所有内容。那是你会怎么做的?
解决方法
我猜想其他属性是根据用户在注册过程中选择的内容预先确定的?
在这种情况下,我将向您的模型添加一个“ 0”钩子,以计算并相应地分配这些属性:
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
, 根据Dan的方法,您还可以为角色恕我直言添加新的“ PlayerClass”模型。它可以与您的玩家或角色类具有一个属一个属,因此您可以拥有许多关系。这样,如果您需要更多的类,则可以通过ui中的admin控件将其添加,然后将其直接添加到数据库中。
只是另一件事:)