快速总结:我有一个Rails应用程序,它是一个个人清单/待办事项列表。基本上,您可以登录并管理您的待办事项列表。
我的问题:当用户创建一个新帐户时,我想要填充他们的清单中的20-30个默认的待办项目。我知道我可以说:
wash_the_car = ChecklistItem.new
wash_the_car.name = 'Wash and wax the Ford F650.'
wash_the_car.user = @new_user
wash_the_car.save!
...repeat 20 times...但是,我有20行ChecklistItem行要填充,所以这将是60行非常潮湿的代码(也称为非干代码)。一定有更好的办法。
因此,在创建帐户时,我希望使用YAML文件中的ChecklistItems表。YAML文件可以填充我的所有ChecklistItem对象。当一个新用户被创建时-- bam!--预设的待办项目在他们的列表中。
我该怎么做?
谢谢!
(PS:对于那些想知道我为什么要这么做的人来说:我正在为我的网页设计公司做一个客户登录。我有20个步骤(第一次会议、设计、验证、测试等)。我和每个网络客户端一起经历过。这20个步骤是我想为每个新客户端填充的20个核对表项。然而,虽然每个人都从相同的20项开始,但我通常会根据项目定制将要采取的步骤(因此,我将使用普通的to列表实现,并希望以编程方式填充行)。如果你有问题,我可以进一步解释。
发布于 2009-05-12 15:08:52
我同意其他人的建议,你只需要用密码就行了。但它不必像建议的那样冗长。如果你想要的话,它已经是一条线了:
@new_user.checklist_items.create! :name => 'Wash and wax the Ford F650.'将其放入从文件中读取的项的循环中,或存储在类中或其他地方:
class ChecklistItem < AR::Base
DEFAULTS = ['do one thing', 'do another']
...
end
class User < AR::Base
after_create :create_default_checklist_items
protected
def create_default_checklist_items
ChecklistItem::DEFAULTS.each do |x|
@new_user.checklist_items.create! :name => x
end
end
end或者,如果项的复杂性增加,请用散列数组替换字符串数组.
# ChecklistItem...
DEFAULTS = [
{ :name => 'do one thing', :other_thing => 'asdf' },
{ :name => 'do another', :other_thing => 'jkl' },
]
# User.rb in after_create hook:
ChecklistItem::DEFAULTS.each do |x|
@new_user.checklist_items.create! x
end但我并不是真的建议您将所有缺省值都抛到ChecklistItem内部的一个常量中。我就是这样描述的,这样您就可以看到Ruby对象的结构了。相反,将它们放入您一次读取的YAML文件中并缓存:
class ChecklistItem < AR::Base
def self.defaults
@@defaults ||= YAML.read ...
end
end或者,如果您希望管理员能够动态地管理默认选项,请将它们放在数据库中:
class ChecklistItem < AR::Base
named_scope :defaults, :conditions => { :is_default => true }
end
# User.rb in after_create hook:
ChecklistItem.defaults.each do |x|
@new_user.checklist_items.create! :name => x.name
end有很多选择。
发布于 2009-05-11 11:12:26
只需编写一个函数:
def add_data(data, user)
wash_the_car = ChecklistItem.new
wash_the_car.name = data
wash_the_car.user = user
wash_the_car.save!
end
add_data('Wash and wax the Ford F650.', @user)发布于 2009-05-11 11:09:15
Rails夹具用于填充单元测试的测试数据;不要认为它是在您提到的场景中使用的。
我想说的是,只要提取一个新的方法add_checklist_item并完成它。
def on_user_create
add_checklist_item 'Wash and wax the Ford F650.', @user
# 19 more invocations to go
end如果你想要更多的灵活性
def on_user_create( new_user_template_filename )
#read each line from file and call add_checklist_item
end该文件可以是一个简单的文本文件,其中每一行对应一个任务描述,比如"Wash和Wash The Ford F650“。用Ruby写应该很容易,
https://stackoverflow.com/questions/847586
复制相似问题