繁体   English   中英

Rails应用程序和sqlite(dev)与Postgresql(产品)

[英]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 ,以下代码根据帐户是否处于活动状态输出truefalse

<% @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不会输出truefalse

为什么会这样,我该如何解决?

纸轨日志:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM