开发者

get auto_increment value, with build?

In my user registration routine, i have this code :

@user = User.new(attribs)  

@user.build_inventory(:max_slots => 10) # create the user inventory, starting with 10 slots

success = @user && @user.save
if success && @user.errors.empty?

This works great in creating an inventory and a user bound to that inventory. However, now i want to add a new inventory_item in every registration. I tried something like :

@user = User.new(attribs)  

inventory = @user.build_inventory(:max_slots => 10) # create the user inventory, starting with 10 slots
InventoryItem.create(:inventory_id => inventory.id, :game_item => GameItem.find_by_n开发者_JAVA百科ame('Fist'), :is_equipped => 1)

I thought it would not work (beacuse inventory is not built before inventory_item, and of course it didn't. What is the correct way to do that ?


The best way of automatically adding an item to the inventory would be to do so in the inventory model. There, you can add an after_create method that will run every time an inventory is created. This way, you can remove this added layer of complexity from your model, and don't have to worry about the inventory id.

class Inventory < ActiveRecord::Base
  # other associations
  has_many :inventory_items

  after_create :create_starting_items

  protected
    def create_starting_items
      inventory_items.create do |item|
        item.game_item   = GameItem.find_by_name('Fist')
        item.is_equipped = true # This should likely be a boolean
      end
    end
end

You can extend this functionality to the user model and create the inventory as an after_create as well, allowing the controller to only create the user and have the model(s) take care of associated inventories and items.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜