2011-05-30 138 views
3

我有一个用户注册,用户在其中设置用户名,first_class和其他attribs。现在,我还需要设置一些其他属性,例如:str或:acc。在这种情况下如何处理质量分配

这些属性可能会在创建一个质量分配命令中设置。当然,我不想单独为每一个做update_attribute。因此,我必须让他们attr_accessible。

但是,我不希望用户设置它们。例如,如果用户决定使用first_class ='Ranger',我会设置他的:str而不是他。

我的想法是,我只会保存params [:first_class]或params [:username],并明确地为我的创建方法中的其他设置为用户。你是这么做的吗?

+0

听起来像一个很好的游戏。请通知我,当这出来:) – corroded 2011-05-30 05:50:57

+0

哈哈thanx:D它需要sooooo很多时间,你们帮助很多:) – Spyros 2011-05-30 05:53:38

回答

6

我猜测其他属性是根据用户在注册过程中选择的内容预先确定的?

在这种情况下,我会一个before_create钩添加到您的模型,计算并分配相应的属性:

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 
+0

ahhh伟大的处理。这个不需要:str,:dex和:wis被声明为attr_accessible? – Spyros 2011-05-30 05:56:45

+0

nope,因为它们是在内部分配的,而不是作为批量更新的一部分。 – 2011-05-30 05:58:44

+0

非常感谢你:) – Spyros 2011-05-30 06:00:13

2

基于丹的方法,你也可以只添加一个新的“PlayerClass”模型你的性格恕我直言。它可以与你的玩家或角色类有一个belongs_to的关系,所以你可以拥有很多这样的关系。这样,如果你需要更多的类,你可以通过你的UI中的管理控件添加它,并直接将其添加到数据库。

只是另一个承担:)