mardi 1 décembre 2015

Foreign key validation in rails

I am trying to design a database with a 1 to many relationship where 1 parent can have many children. The database seems to work OK. I am trying to write integration tests to check for invalid data and that works OK, but it fails when I try inputting valid data into the database. It gives me a similar error to below. Am I doing something wrong in my code, or could it be a problem with my test?

This isn't my actual code, but I think it is representative

When I output the child.errors

#<Parent id: 980190963, parent_id: 2,...>
#<ActiveModel::Errors:0xXX @base=#<Parent id: nil, parent_id: 2
   ,..., @messages={:parent=>["can't be blank"]}>

Integration Test

# insert valid data where parent_id does exist
assert_equal 201, response.status

Failed Test

1) Failure:
   ParentTest#test_log_valid [...]
   Expected: 201
   Actual: 422

Child Migration

class CreateChild < ActiveRecord::Migration
  def change
    create_table :children do |t|
      t.integer :parent_id
      t.timestamps null: false
    end
    add_index :children, :parent_id
  end
end

Parent Migration

class CreateParents < ActiveRecord::Migration
  def change
    create_table :parents do |t|
      t.integer :parent_id
      t.timestamps null: false
    end
    add_index :parents, :parent_id
  end
end

Parent Model

class Parent < ActiveRecord::Base
  has_many :children
end

Child Model

class Child < ActiveRecord::Base
  belongs_to :parent
  validates :parent, presence: true
end

Aucun commentaire:

Enregistrer un commentaire