我正在开发一个 Rails Web 应用程序,但对如何在我的模型中使用查找表值感到困惑。这是我的应用程序中的示例模型:
table name: donations
id
amount
note
user_id
appeal_id
donation_status_id
donation_type_id
is_anonymous
created_at
updated_at
字段 *donation_status_id* 和 *donation_type_id* 指的是查找表。所以在我的代码中,我有几个随机的地方,我可以这样调用:
my_donation = Donation.find(params[:id])
if my_donation.donation_status_id == DonationStatus.find_by_name("completed").id
#do something
end
在我没有经验的眼中,对 DonationStatus 表的一次性查询在这里似乎非常浪费,但我没有看到任何其他好的方法来做到这一点。我想到的第一个想法是在应用程序启动时将我所有的查找表读入一个散列,然后在需要时查询它。
但是有没有更好的方法来做我想做的事情?我不应该担心这样的查询吗?
谢谢!
最佳答案
由于您有两个模型,因此在构建模型时应该使用 ActiveRecord 模型关联。
class Donation
has_one :donation_status
end
class DonationStatus
belongs_to :donation
end
然后当你做
my_donation = Donation.find(params[:id])
if my_donation.donation_status.status_name == 'complete'
#do something
end
有关更多信息,您可能需要阅读 rails 如何进行模型关联 http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html不要担心性能,如果您按照应该的方式进行操作,Rails 已经为您处理好了
关于ruby-on-rails - 我想将我的数据库查找表映射到散列,好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6880485/