如何为 Rails 迁移定义布尔字段

发布于 2024-10-15 20:46:32 字数 403 浏览 5 评论 0原文

我想向表“my_model”添加一个布尔字段(“is_public”)。目前,我可以使用这个:

class AddPublicToDream < ActiveRecord::Migration
  def self.up
    add_column :my_model, :is_public, :string
  end

  def self.down
    remove_column :my_model, :is_public, :string
  end      
end

然后我可以在控制器中为 mymodel.is_public 分配“true”或“false”。

我可以用 :boolean 替换 :string 来达到相同的效果吗?与 :string 相比,它会节省一些数据库空间吗?

I want to add a boolean field ("is_public") to the table "my_model". Currently, I can use this:

class AddPublicToDream < ActiveRecord::Migration
  def self.up
    add_column :my_model, :is_public, :string
  end

  def self.down
    remove_column :my_model, :is_public, :string
  end      
end

Then I can assign "true" or "false" to mymodel.is_public in controllers.

Can I substitute :string with :boolean to achieve the same effect? Would it save some database space compared to :string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

メ斷腸人バ 2024-10-22 20:46:32

是的,您可以使用 :boolean 来实现此目的,是的,它还会节省数据库空间。

Yes, you can use :boolean for this, and yes it will also save database space.

莫相离 2024-10-22 20:46:32

将 type 属性更改为 :boolean 并再次运行 rake db:migrate。您应该能够调用,例如:

Dream.is_public?  # returning true or false depending whether is set.

Change the type attribute to :boolean and run rake db:migrate again. You should be able to call, for example:

Dream.is_public?  # returning true or false depending whether is set.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文