![](/img/trans.png)
[英]Ruby on Rails: Query in model for SQLite in Dev => PostgreSQL in Prod
[英]Rails app and sqlite (dev) vs postgresql (prod)
我正在學習RoR,並且我的開發數據庫是默認數據庫sqlite,並且正在將我的應用程序部署到使用posgresql的Heroku。 我知道要避免此類問題,我也應該使用postgresql進行開發,將來我打算這樣做。 但是,我有一個問題出現在生產環境中,但沒有出現在開發人員中。
問題 :我有一個User
和一個Account
模型。 一個User
可以有多個Accounts
。
我進行了遷移,以便在創建Account
時,默認情況下其active
字段設置為true
。
class UpdateDefaultAccountActiveValue < ActiveRecord::Migration
def change
change_column_default(:accounts, :active, true)
end
end
這似乎在開發人員中起作用。
在/views/accounts/index.html.erb
,以下代碼根據帳戶是否處於活動狀態輸出true
或false
。
<% @accounts.each do |account| %>
<tr>
<% if !(account.credit) %>
<td><%= link_to account.name, history_url(id: account.id) %></td>
<% else %>
<td><%= link_to account.name + ' (Credit)', history_url(id: account.id) %></td>
<% end %>
<td><%= account.active %></td>
<td><%= link_to 'Edit', edit_account_path(account) %></td>
</tr>
<% end %>
但是,在生產中,根據帳戶是否處於活動狀態,/ /views/accounts/index.html.erb
不會輸出true
或false
。
為什么會這樣,我該如何解決?
紙軌日志:
2016-05-25T21:34:06.348465+00:00 app[web.1]: Started GET "/accounts" for 176.248.123.34 at 2016-05-25 21:34:06 +0000
2016-05-25T21:34:06.355649+00:00 app[web.1]: Processing by AccountsController#index as HTML
2016-05-25T21:34:06.447420+00:00 app[web.1]: Completed 200 OK in 94ms (Views: 64.5ms | ActiveRecord: 18.2ms)
2016-05-25T21:34:06.452111+00:00 heroku[router]: at=info method=GET path="/accounts" host=???.herokuapp.com request_id=f33ab960-5c1b-4883-a28c-8c2b40388bad fwd="176.248.123.34" dyno=web.1 connect=0ms service=107ms status=200 bytes=4073
這可能無法解決您遇到的確切問題,但是與布爾標志相比,有一種更好的方法將不同的狀態添加到模型中。
ActiveRecord :: Enum可以創建一個枚舉屬性,其中值映射到數據庫中的整數。
class Account
enum status: [:active, :closed, :supended] # basically whatever you want
end
Acount.active # => Acount.where(status: :active)
acount.active! # => Acount.update!(status: :active)
acount.active? # => true
acount.closed? # => false
acount.suspended? # => false
acount.status # => "active"
當然,您需要將整數列添加到數據庫中:
rails g migration add_status_to_accounts status:integer:index
不要遷移它! 我們還想添加一個默認值:
class AddStatusToAccounts < ActiveRecord::Migration
def change
add_column :accounts, :status, :integer, default: 0, null: false
add_index :accounts, :status
end
end
為了在創建記錄時設置模型屬性,必須在模型內部對其進行更改,如果運行遷移,它將僅對現有記錄有所幫助。
您需要在模型中添加三行代碼,以使其適用於創建的新帳戶:
before_save do
self.active = true
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.