如何获取表列值?

问题描述:

我写的后续代码从表webeehs得到一个记录:如何获取表列值?

webeehs_result = Webeeh.find(:all, :conditions=>["webeeh_project_id=#{project_id}"]) 

然后,我想从这个纪录一列值,我该怎么办?
例如,列名是webeeh_date

首先,永远不要写这样的代码。以纯字符串的形式构建自己的条件会使您容易受到SQL注入漏洞攻击。如果必须这样做的条件,然后再去做这样的:

:conditions => ["webeeh_project_id = ?", project_id] 

,如果你有一个项目的模型,你应该从你Webeeh模式webeeh_project_id列重命名为project_id和有像has_many :webeehs

在您的项目模型的关联

然后,您将不需要再拨打该电话,只需执行p = Project.find(id),然后p.webeehs将返回所需的webeeh。

结果将是一个可以迭代的数组。并让你的webeeh.webeeh_date成员,只是把它像这样:

result.each do |webeeh| 
    date = webeeh.webeeh_date 
end 
+0

我知道。谢谢。 – Norah 2011-01-27 08:46:41

webeeh_result通常是数据库结果数组。

您可以重复使用throughit

 
webeehs_result.each do |webeeh| 

# use "webeeh.webeeh_date" to access the column_name or do whatever you want with it. 

end 

webeehs_result = Webeeh.findwebeeh_dates 

是足以让所有columnn值。

对于不同的方法和性能问题,请检查以下内容:http://www.stopdropandrew.com/2010/01/28/finding-ids-fast-with-active-record.html