I'm using SQlite for development environment and Postgre for Production.
At the development everything works nicely. But when I try to reset and to migrate the production Database I received the following message:
PG::UndefinedTable: ERROR: relation "priceranges" does not exist
...
FOREIGN KEY ("pricerange_id")
REFERENCES "priceranges" ("id")
My venue model:
belongs_to :pricerange, :class_name => "PriceRange"
My pricerange migration:
class CreatePriceRanges< ActiveRecord::Migration[5.0]
def change
create_table :price_ranges do |t|
t.string :price_description
t.timestamps
end
end
end
Any ideas?
The table name you are creating in your migration is price_ranges, not priceranges. Unless you are overriding the table name in the PriceRange model, your pricerange association on Venue will look for a foreign key named price_range_id, not pricerange_id. I would recommend sticking with convention, and making your association:
belongs_to :price_range # automatically uses class PriceRange, and foreign key `price_range_id`
Related
I have two models:
class BracketMatch < ActiveRecord::Base
belongs_to :match
belongs_to :bracket
end
and
class Bracket < ActiveRecord::Base
has_many :bracket_matches
# Has a STI column
end
I am trying to add a foreign key to the table bracket_matches.
add_foreign_key :bracket_matches, :brackets
Raises the following error
PG::ForeignKeyViolation: ERROR: insert or update on table "bracket_matches" violates foreign key constraint "fk_rails_39684e0d9b"
DETAIL: Key (bracket_id)=(122) is not present in table "brackets".
: ALTER TABLE "bracket_matches" ADD CONSTRAINT "fk_rails_39684e0d9b"
FOREIGN KEY ("bracket_id")
REFERENCES "brackets" ("id")
What am I doing wrong and why is it checking bracket_id on brackets instead of bracket_matches?
rails g migration AddFieldToBracketMatches bracket:references
Check your migration file and then rake db:migrate
Edit
In that case why not just rails g migration RemoveColumnFromBrackMatches , remove_column :bracket_matches, :bracket , rake db:migrate, then delete both those migration files and create the migration I suggested above
Add index:true like this
add_foreign_key :bracket_matches, :brackets ,index:true,foreign_key:true
In my rails application I have multiple postgresql schemas.
SHOW search_path;
search_path
--------------
"$user",public,vehicle
I have two tables (dealers, inventories) in the vehicle schema. The relationship holds like this:
dealer has_many inventories
inventory belongs_to dealer
I created a migration to add the relationship as:
class AddDealerIdToVehicleInventories < ActiveRecord::Migration
def change
add_reference 'vehicle.inventories', :dealer, index: true, foreign_key: {on_delete: :cascade}
end
end
This migration works perfectly when I run: rake db:migrate, the foreign_key seems added to the table without any issue. But when I run rake db:rollback, I am getting this error message:
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedColumn: ERROR: column "vehicle.dealer_id" referenced in foreign key constraint does not exist
: ALTER TABLE "vehicle"."inventories" ADD CONSTRAINT "fk_rails_95ee16593d"
FOREIGN KEY ("vehicle.dealer_id")
REFERENCES "vehicle"."dealers" ("id")
ON DELETE CASCADE
I am not sure if I am making any mistakes or is the rails migration bug. Thanks for the help.
I solved the issue by making changes in the migration file as:
class AddDealerIdToVehicleInventories < ActiveRecord::Migration
def up
add_reference 'vehicle.inventories', :dealer, index: true, foreign_key: {on_delete: :cascade}
end
def down
execute <<-SQL
ALTER TABLE vehicle.inventories
DROP COLUMN dealer_id
SQL
end
end
Hope, this is useful for others too.
I have an already existing database schema with tables that have a string column as primary key and also some tables with more than one columns as key. I would like to map this schema in rails, but I dont know how to override the default primary key (a column id created by the rails framework).
You can override the primary key like this
class Book < ActiveRecord::Base
self.primary_key = 'author'
end
I don't know what you're trying to do. It's a mistake altering primary key in Rails.
But for that matter try to do it in your migration.
class Foos < ActiveRecord::Migration
def self.up
create_table :foos, :id => false do |t|
t.string :my_id
t.timestamps
end
end
end
I have a ruby model called MyModelA and MyModelB as shown below
class MyModelA < ActiveRecord::Base
belongs_to :mymodelb
class MyModelB < ActiveRecord::Base
# Blah Blah Blah
When I create the database with rake db:create command, I notice that MYMODELA table doesn't have a foreign key constraint on it. I manually inserted it like this:
ALTER TABLE MYMODELA ADD FOREIGN KEY (MYMODELB_ID) REFERENCES MYMODELB(ID);
How can I define my model such that this DB foreign key constraint is automatically created without me having to manually add it later?
Rails doesn't provide a migration helper to add foreign_key. But you can use foreigner gem
You do do this to add a foreign_key using foreigner gem
create_table :products do |t|
t.string :name
t.integer :factory_id
t.foreign_key :factories
end
generate a migration:
rails g migration AddmymodelbidToMyModelA mymodelb_id:integer
go the the migration file and add
add_index :mymodela, :mymodelb_id
just between the two end clauses
run rake:db:migrate
Is there any difference between using t.references and executing SQL command to create foreign key relationship between products and category table as shown below? In other words, are the two different ways of doing the same thing or am I missing anything here?
class ExampleMigration < ActiveRecord::Migration
def up
create_table :products do |t|
t.references :category
end
#add a foreign key
execute <<-SQL
ALTER TABLE products
ADD CONSTRAINT fk_products_categories
FOREIGN KEY (category_id)
REFERENCES categories(id)
SQL
add_column :users, :home_page_url, :string
rename_column :users, :email, :email_address
end
def down
rename_column :users, :email_address, :email
remove_column :users, :home_page_url
execute <<-SQL
ALTER TABLE products
DROP FOREIGN KEY fk_products_categories
SQL
drop_table :products
end
end
They're not the same thing. Rails by default doesn't enforce foreign keys in the database. Instead, references when creating from the command line also creates a regular index, like this:
add_index :products, :category_id
Update:
Rails 5 actually does exactly the same thing now. So, to answer the original question: Nowadays, both are the same.
I found some thing intresting in this page.
http://railsforum.com/viewtopic.php?id=17318
From a comment :
Rails doesn't use foreign keys to perform his backend tasks. This
because some db like sqlite doesn't allow foreign keys on its tables.
So Rails doesn't provide an helper to build a foreign key
Also there is a gem foreigner for adding foreign keys to database table.
What creates the FOREIGN KEY constraint in Ruby on Rails 3?