我在保存模型时遇到了一些麻烦
class AmazonMovie < ActiveRecord::Base
attr_accessible :asin_buy, :asin_rent, :movie_id, :on_prime, :on_prime_prev, :price_buy, :price_buy_prev, :price_rent, :price_rent_prev, :url, :updated_at, :created_at
belongs_to :movie
has_many :amazon_movie_changes, :dependent => :destroy
validates :movie_id, presence: true, uniqueness: true
AWS_QPS_THRESHOLD = 1.0
before_create :init
def init
self.on_prime_prev = false
end
def update_changes
...
还有另一个班级
class AmazonMovieChange < ActiveRecord::Base
attr_accessible :amazon_movie_id, :buy_change, :movie_id, :on_prime, :on_prime_prev, :price_buy, :price_buy_prev, :price_rent, :price_rent_prev, :prime_change, :rent_change
belongs_to :movie
belongs_to :amazon_movie
validates_presence_of :movie_id, :amazon_movie_id
...
当我创建如下模型时:
=> #<AmazonMovie id: nil, movie_id: 16918, asin_buy: "B00FSTCUGA", price_buy: 7.99, price_buy_prev: nil, asin_rent: "B00FST7SX0", price_rent: 3.99, price_rent_prev: nil, on_prime: false, on_prime_prev: false, url: "http://www.amazon.com/Strongman-Stanless-Steel/dp/B...", created_at: nil, updated_at: nil>
我收到以下保存失败:
ActiveRecord::RecordInvalid: Validation failed: Amazon movie changes is invalid
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/validations.rb:56:in `save!'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/attribute_methods/dirty.rb:33:in `save!'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:246:in `block in save!'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:295:in `block in with_transaction_returning_status'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/database_statements.rb:192:in `transaction'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:208:in `transaction'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:293:in `with_transaction_returning_status'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:246:in `save!'
from (irb):145
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.8/lib/rails/commands/console.rb:47:in `start'
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.8/lib/rails/commands/console.rb:8:in `start'
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
更新: 我意识到删除before_create:init这个模型保存没有错误。我最初的意图是将此字段默认为false而不是NULL。我的语法有问题吗?或者这不是默认字段的正确方法吗?