开发者

Required Foreign Key is Being Saved as Null

I have a Rails app that has "Datapoint" and "Dataset" model objects. Datasets belog to Datapoints.

models/dataset.rb:

# Table name: datasets
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  created_at :datetime
#  updated_at :datetime

class Dataset < ActiveRecord::Base
  belongs_to :user
  validates :name, :presence => true
end

models/datapoint.rb:

# Table name: datapoints
#
#  id         :integer         not null, primary key
#  dataset    :integer
#  date       :date
#  value      :float
#  created_at :datetime
#  updated_at :datetime

class Datapoint < ActiveRecord::Base
  belongs_to :dataset
  validates :date, :presence => true
  validates :dataset, :presence => true
  validates :value, :presence => true
end

My controllers/datapoints_controller.rb successfully saves datapoints records:

class DatapointsController < ApplicationController
  def create
    @datapoint = Datapoint.new(params[:datapoint])
    @datapoint.dataset = Dataset.find(current_user.dataset)
    if @datapoint.save
      redirect_to root_path
    else
    end  
  end
end

However, when I look in my database, the dataset field for each datapoint entry (which is a required foreign key) is empty. How is this possible? 开发者_JS百科


Looks like a bad migration (wrong field name for foreign key):

# Table name: datapoints
#  dataset    :integer <<<< This should be dataset_id
#  date       :date
...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜