开发者

Form not using default values from migration

开发者 https://www.devze.com 2023-01-06 11:58 出处:网络
So I have model with an association and I\'m using a single form with \"accepts_nested_attributes_for\" to create records.In 开发者_运维技巧the form I have a few select drop downs for the child that a

So I have model with an association and I'm using a single form with "accepts_nested_attributes_for" to create records. In 开发者_运维技巧the form I have a few select drop downs for the child that aren't always required to have a selected value and when that situation happens I want to use the default value I've specified in my migration.

So if I submit the form without selecting anything from the drop downs I get Mysql complaining about trying to insert NULL. I thought somewhere along the lines the empty string from the form would use the default migration value/default value in mysql instead of trying to insert NULL?

Am I missing something? Thanks in advance.

Edit: Some code ... (simplified). "book_type" should really be "book_type_id", but disregard that.

Mysql error msg:

Mysql::Error: Column 'book_type' cannot be null: INSERT INTO book_details (book_id, book_type, ...) VALUES(1, NULL, ...)

Migration:

class CreateBookDetails < ActiveRecord::Migration
  def self.up
    create_table :book_details do |t|
      t.integer :book_id, :null => false, :default => 0
      t.integer :book_type, :null => false, :default => 0
      ...

      t.timestamps
    end
  end

  def self.down
    drop_table :book_details
  end
end


you have 3 choices:

1- change your migration, delete the ":null => false" to avoid errors. you said that in some cases it may be not selected, right?

2- edit the model and add a before_save callback to change to "0" the value if it was left blank in the form.

3- create an "option" in the dropdown list with some empty label and "0" as its value. this way when submit the form, the value remains at least 0 (as defined in migration)

it depends by your needs ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号