In Rails, how do you assign all attributes of an item automatically depending on the first attribute

坚强是说给别人听的谎言 提交于 2019-12-12 06:36:56

问题


Basically, I want to generate an item, in this case, a ring. I have different TYPES of rings:

class Ring < ActiveRecord::Base

  DISPLAY_NAMES [ 'Silver', 'Gold', 'Diamond' ]

  attr_accessible :description, :display_name, :roll, :bonus, :total, :image, :gold

end

Is there a way to randomize the DISPLAY_NAMES of rings?

I'm guessing something like @ring.display_name = rand(Ring::DISPLAY_NAMES)?

Is there a better way to do this?

Once that is found, is there a way to set all other attributes of the ring, like @ring.roll and @ring.bonus, etc..

For example, if a ring comes up as silver, can I declare in the model some kind of if statement that states if the ring is silver and the other attributes are bla bla bla?

Thanks in advance. Learning slowly but surely.


回答1:


To get a random entry from the DISPLAY_NAMES array do

@ring.display_name = DISPLAY_NAMES.sample

check http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-sample

For the second part, if the rest of the values are static and will not change, then I would just seed them in seed.rb

Populate the db with all the values for each [ 'Silver', 'Gold', 'Diamond' ] So, you will have 3 records in the db for each name.

After that, you can do

@ring = Ring.find_by_display_name(DISPLAY_NAMES.sample)


来源:https://stackoverflow.com/questions/11250930/in-rails-how-do-you-assign-all-attributes-of-an-item-automatically-depending-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!