English 中文(简体)
从铁路模型返回的默认值放在何处?
原标题:Where to place a default value to return from a Model in Rails?

我有一个叫城市的模特

我有几个方法根据不同属性(接近拉链码的城市,按人口统计的城市)寻找城市。然而,如果找不到城市,我想违约到某个城市,请换句话说,纽约就是了。

所以我发现自己经常这样做:

@city = City.find_by_zip_code(83030)
if @city.nil?
 @city = City.find_by_name( New York )
end

这只是我用拉链代码看的方法, 但我总是用几种方法这样做。 我在哪里以及如何集中使用这个默认值 :

City.find_by_name( New York )

编辑:

采用这样的方法是否是一个好主意?

def self.default_city
 @default_city = City.find_by_name( New York )
end

避免每次我想拿到默认城市时都获取数据库?

最佳回答

您至少可以更容易地打字 :

@city = City.find_by_zip_code(83030) || City.find_by_name( New York )

为了避免额外的 db 点击, 缓存默认值 :

def self.default_city
  Rails.cache.fetch( default_city ) do
    City.find_by_name( New York )
  end
end

I have a blog post with a few more details about caching like that: http://www.tmatthew.net/blog/rails-caching-example

问题回答

在活动记录: Base中查找_or_ 初始化_by_

http://api.rubyonrails.org/class/ActiveRecord/Base.html





相关问题
Having models declarations at two folders in Django

How can you have model declarations at two different directories in Django? I have the model at the directory Code which contains "init.py", "models.py" and "admin.py". It is working properly alone. ...

zend modules models

My application setup with 2 modules admin and default I test the controller which works fine on modules but the models doesnt work I created a model applicationmodulesadminmodelsUser.php <?...

A Friendship relationship question

I am having difficulties with listing this type of data. Scenario is as follows: user1 add s a friend called user2 user2 confirms that user1 is his friend what should happen is user2 and user1 see s ...

Rails data modeling question

I am creating a simple todo app where I have 2 types of tasks. 1) regular tasks - These have a due date 2) recurring tasks -These are poped up as reminders on specified date. They can be created ...

Problems with updating records in django-admin

I m using Django (specifically django-admin) to be the admin panel for a site that uses PHP for client-facing features. I ve been messing around making the admin look exactly the way I want and so far ...

热门标签