ActiveRecord + ActiveAdmin,保存空字符串而不是null

时间:2017-05-03 16:17:44

标签: ruby-on-rails activerecord activeadmin

当我使用Active Admin表单时,空字符串值将保存为"" (空)而不是NULL值。

我是否应该在初始化程序中设置一个参数,以便在MySQL中将每个空值保存为NULL?

import sys
from PyQt4.QtCore import QSize, Qt
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

html = \
"""<html>
<head>
<title>Python Web Plugin Test</title>
</head>

<body>
<h1>Python Web Plugin Test</h1>
<object type="x-pyqt/widget" width="200" height="200"></object>
<p>This is a Web plugin written in Python.</p>
</body>
</html>
"""

class WebWidget(QWidget):

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.setBrush(Qt.white)
        painter.setPen(Qt.black)
        painter.drawRect(self.rect().adjusted(0, 0, -1, -1))
        painter.setBrush(Qt.red)
        painter.setPen(Qt.NoPen)
        painter.drawRect(self.width()/4, self.height()/4,
                         self.width()/2, self.height()/2)
        painter.end()

    def sizeHint(self):
        return QSize(100, 100)

class WebPluginFactory(QWebPluginFactory):

    def __init__(self, parent = None):
        QWebPluginFactory.__init__(self, parent)

    def create(self, mimeType, url, names, values):
        if mimeType == "x-pyqt/widget":
            return WebWidget()

    def plugins(self):
        plugin = QWebPluginFactory.Plugin()
        plugin.name = "PyQt Widget"
        plugin.description = "An example Web plugin written with PyQt."
        mimeType = QWebPluginFactory.MimeType()
        mimeType.name = "x-pyqt/widget"
        mimeType.description = "PyQt widget"
        mimeType.fileExtensions = []
        plugin.mimeTypes = [mimeType]
        print "plugins"
        return [plugin]

if __name__ == "__main__":

    app = QApplication(sys.argv)
    QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True)
    view = QWebView()
    factory = WebPluginFactory()
    view.page().setPluginFactory(factory)
    view.setHtml(html)
    view.show()
    sys.exit(app.exec_())

这是我的迁移架构:

form do |f|
    input :label
    input :description, as: :text
    input :country
    input :city
  end
  actions
end

这是我的Gemfile。

create_table "projects" do |t|
  t.string "label", limit: "40"
  t.string "country", limit: "2"
  t.string "city", limit: "200"
  t.string "description", limit: 600
end

2 个答案:

答案 0 :(得分:1)

这似乎是表单的默认行为。我来到这个宝石nilify_blanks,这将解决你的问题。 希望它有所帮助。

答案 1 :(得分:1)

这是一个Rails,而不是ActiveAdmin问题。

如果可以,don't use null for empty strings。使用null可能在理论上是正确的,但实际上我发现如果所有varchar列都设置为null,则使用MySQL更简单且更不容易出错,例如:

New   | Line  | data

自Rails 4以来,nilify_blanks gem未被维护。相反,请在模型中尝试以下内容:

t.string :label, limit: 40, null: false