I have a error without explanation.
My error :
G::UndefinedColumn: ERROR: column "conjoncture_index_id" referenced in foreign key constraint does not exist
: ALTER TABLE "reports" ADD CONSTRAINT "fk_rails_c25ad9a112"
FOREIGN KEY ("conjoncture_index_id")
REFERENCES "conjoncture_indices" ("id")
My migration :
class AddColumnToReports < ActiveRecord::Migration
def change
add_reference :reports, :conjoncture_indice, index: true
add_foreign_key :reports, :conjoncture_indices
end
end
My create table migration :
class CreateConjonctureIndices < ActiveRecord::Migration
def change
create_table :conjoncture_indices do |t|
t.date :date
t.float :value
t.timestamps null: false
end
end
end
My model :
class ConjonctureIndice < ActiveRecord::Base
has_many :reports
by_star_field :date
end
My ConjonctureIndice shema.rb part :
create_table "conjoncture_indices", force: :cascade do |t|
t.date "date"
t.float "value"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
I'm looking for "conjoncture_index" in my project but nothing... I think that a old version of the project uses "conjoncture_index" instead "conjoncture_indice" but all occurence are deleted.
In rails , The migration names are plural whereas the model names are singular . So the model name should had been Index but it cannot be as it's a reserved keyword , the plural of which transforms to ConjunctureIndices .
Note - If you are still in doubt , then you can drop and re-create the database but i suspect the naming convention to be an issue in your case .
Ok i found the problem. i think that the error message is the same as before but he refer to a other table called "confidence_indices". The error come from "indice" word.. when i delete it i have no problem.
Related
Issue is I can't find why reference column id can't be inserted when create new record.
I have 3 table shop_plan, shop and app
Below is tables schema:
create_table "shop_plans", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "shops", force: :cascade do |t|
t.string "url"
t.bigint "plan_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["plan_id"], name: "index_shops_on_plan_id"
end
create_table "apps", force: :cascade do |t|
t.bigint "shop_id"
t.binint "amount"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["app_id"], name: "index_apps_on_shop_id"
end
add_foreign_key "shops", "shop_plans", column: "plan_id"
add_foreign_key "apps", "shops"
And below is Model
class ShopPlan < ApplicationRecord
has_many :shop
end
class Shop < ApplicationRecord
belongs_to :shop_plan, class_name: 'ShopPlan', foreign_key: :plan_id
has_many :app
end
class App < ApplicationRecord
belongs_to :shop, class_name: 'Shop', foreign_key: :shop_id
end
There will be 1 default record added in seed.db for table shop_plan
ShopPlan.create(name: 'Basic')
ShopPlan and Shop are linked by plan_id column in Shop
Shop and App are linked by shop_id column in App
I pre-insert some value when user access index:
#basic_plan
#basicPlan = ShopPlan.where(name: "Basic").first
# if new shop registered, add to database
unless Shop.where(url: #shop_session.url).any?
shop = Shop.new
shop.url = #shop_session.url
shop.plan_id = #basicPlan.id
shop.save
end
This insert works well, however, when i run 2nd insert:
#shop= Shop.where(url: #shop_session.url).first
unless App.where(shop_id: #shop.id).any?
app = App.new
app.shop_id = #shop.id,
app.amount = 10
app.save
end
error occurs as somehow app.shop_id will not add in my #shop.id and it will return will error: {"shop":["must exist"]}
I even try hard-code app.shop_id =1 but it does not help and when I add in optional: true to app.db model, it will insert null
Appreciate if anyone can help point out why I get this error
EDIT: #arieljuod to be clear
1) I have to specific exact column class due to between Shop And Shop_Plan, i'm using a manual plan_id instead of using default shopplans_id columns.
2) I have update 1 column inside App and all that unless is just to do checking when debugging.
First of all, like #David pointed out, your associations names are not right. You have to set has_many :shops and has_many :apps so activerecord knows how to find the correct classes.
Second, you don't have to specify the class_name option if the class can be infered from the association name, so it can be belongs_to :shop and belongs_to :shop_plan, foreign_key: :plan_id. It works just fine with your setup, it's just a suggestion to remove unnecesary code.
Now, for your relationships, I think you shouldn't do those first any? new block manually, rails can handle those for you.
you could do something like
#basicPlan = ShopPlan.find_by(name: "Basic")
#this gives you the first record or creates a new one
#shop = #basicPlan.shops.where(url: #shop_session.url).first_or_create
#this will return the "app" of the shop if it already exists, and, if nil, it will create a new one
#app = #shop.app or #shop.create_app
I have found out the silly reason why my code does not work.
It's not because as_many :shops and has_many :app and also not because my code when creating the record.
It just due to silly comma ',' when creating new record in App at app.shop_id = #shop.id,, as I was keep switching between Ruby and JavaScript. Thank you #arieljuod and #David for your effort
So I've been successfully creating join tables by using the name parameter when adding an index, but I'm not sure why this isn't working when I'm trying to do create a new migration:
class CreateVMailCampaignScheduleHours < ActiveRecord::Migration[5.1]
def change
create_table :v_mail_campaign_schedule_hours do |t|
t.belongs_to :v_mail_campaign_schedule, foreign_key: true
t.string :day
t.time :start_hours
t.time :stop_hours
t.timestamps
end
add_index [:v_mail_campaign_schedule_hours, :v_mail_campaign_schedule_id], name: :v_mail_campaign_schedule_id
end
end
The error I get is:
ArgumentError: Index name
'index_v_mail_campaign_schedule_hours_on_v_mail_campaign_schedule_id'
on table 'v_mail_campaign_schedule_hours' is too long; the limit is 64
characters
Any suggestions? I thought my add_index would do the trick, but apparently not.
You can change it to the following:
class CreateVMailCampaignScheduleHours < ActiveRecord::Migration[5.1]
def change
create_table :v_mail_campaign_schedule_hours do |t|
t.bigint :v_mail_campaign_schedule
t.string :day
t.time :start_hours
t.time :stop_hours
t.timestamps
end
add_index :v_mail_campaign_schedule_hours, :v_mail_campaign_schedule_id, name: :index_campaign_schedule_hours_on_schedule
end
end
Your approach to create the index manually is the right one. However, t.belongs_to, which is an alias for t.references, instructs the creation of both the foreign key column and the corresponding index. So Rails still tries to create the index, before reaching add_index. Using a simple t.bigint doesn't create the index.
Yeah, so as previously said, t.belongs_to will create an index.
So, I think you can still use create_join_table, but you'll just need to specify index: false on your belongsTo.
create_join_table :v_mail_campaign_schedule_hours do |t|
t.belongs_to :v_mail_campaign_schedule, foreign_key: true, index: false
t.string :day
t.time :start_hours
t.time :stop_hours
t.timestamps
t.index [:v_mail_campaign_schedule_id], name: 'v_mail_campaign_schedule_id'
end
I'm developing my Ruby On Rails application that is using PostgreSQL as a database and I've faced a problem.
Here is my Questions table (schema.rb):
create_table "questions", primary_key: "hashid", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "questions", ["hashid"], name: "index_questions_on_hashid", unique: true, using: :btree
where hashid field (string) is being used instead of a default numeric id field.
Here's my migration for both Questions and Comments tables:
# Questions migration
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions, id: false do |t|
t.text :hashid, primary_key: true
t.string :title
t.text :body
t.timestamps null: false
end
add_index :questions, :hashid, unique: true
end
end
# Comments migration
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :body
t.references :question, foreign_key: :hashid
t.timestamps null: false
end
end
end
I want to relate Comments with Questions in my application using belongs_to and has_many relationship accordingly, but the default t.references :question is trying to relate by using id column from the target table.
Here is the migration error message:
== 20160326185658 CreateComments: migrating ===================================
-- create_table(:comments)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedColumn: ERROR: column "id" referenced in foreign key constraint does not exist
: ALTER TABLE "comments" ADD CONSTRAINT "comments_question_id_fk" FOREIGN KEY ("question_id") REFERENCES "questions"(id)
How could I relate by using other than id field? In my case it is hashid?
I would prefer to still name the primary key column id even when the column contains a random generated string.
To create a string id column in your database, use a migration like this:
create_table :questions, id: false do |t|
# primary key should not be nil, limit to improve index speed
t.string :id, limit: 36, primary: true, null: false
# other columns ...
end
In your model, ensure that a id is created:
class Question < ActiveRecord::Base
before_validation :generate_id
private
def generate_id
SecureRandom:uuid
end
end
When you are already in Rails 5 you might just want to use has_secure_token :id instead of the before_validation call back and the generate_id method.
I have two models connected with a has_and_belongs_to_many association: courses and semesters. rails_admin was only giving me the option to add semesters when creating a course, and not the other way around (and really, it's much more useful to add courses when creating a semester). I made some tweaks the migration:
def change
create_table "courses", force: :cascade do |t|
t.string "department"
t.integer "number"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "semesters", force: :cascade do |t|
t.integer "year"
t.string "season"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "semesters_courses", id: false, force: :cascade do |t|
t.integer "semester_id"
t.integer "course_id"
end
add_index "semesters_courses", ["course_id"], name: "index_semesters_courses_on_course_id"
add_index "semesters_courses", ["semester_id"], name: "index_semesters_courses_on_semester_id"
end
I renamed the intermediary table to semesters_courses from courses_semesters, just for clarity. Not only did this not solve the problem, but now when I try to add a new course, it 500s and tells me:
Could not find table 'courses_semesters'
I know I could make this go away by changing the name back, but I'm not sure where railsadmin is getting that name from (and suspect this to be the source of my problem). I've removed and reinstalled railsadmin, dropped and rewritten the tables, and cleared my browser's cache. When I search my entire project tree for "courses_semesters," I only get results in my error log.
New at Rails dev, so I assume I'm missing some config file somewhere that I need to update, but would love some help on where to find it.
You’re overwriting the join table name.
Option 1 you MUST specify the name of the join table in your models
app/models/course.rb
has_and_belongs_to_many :semesters, join_table: "semesters_courses"
app/models/semester.rb
has_and_belongs_to_many :courses, join_table: "semesters_courses"
Or Option 2 just rename your join table to "courses_semesters" by using migration.
rails g migration rename_courses_semesters
class RenameCoursesSemesters < ActiveRecord::Migration
def self.up
rename_table :semesters_courses, :courses_semesters
end
def self.down
rename_table :courses_semesters, :semesters_courses
end
end
Hope this answers your question.
I use Rails 4, SQLite version 3.8.2 and I would like to add new column to my db.
I create new migration:
rails g migration AddFooToStudents foo:string
so I get then :
class AddFooToStudents < ActiveRecord::Migration
def change
add_column :students, :foo, :string, after: :name
end
end
then I run migration:
rake db:migrate
== 20150803095305 AddFooToStudents: migrating
=================================
-- add_column(:students, :foo, :string, {:after=>:name})
-> 0.0009s
== 20150803095305 AddFooToStudents: migrated (0.0011s)
========================
Everythink seems to be OK, in database has been added foo column but instead of after name column, it has been added at the end of table
ActiveRecord::Schema.define(version: 20150803095305) do
create_table "students", force: :cascade do |t|
t.string "name"
t.string "lastname"
t.integer "age"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "second_name", default: "Untitled"
t.string "foo"
end
end
I completely don't know what I do wrong
You're using the after option, and so you could reasonably expect it to put it after :name.
However, this isn't documented very well (if at all) but the after option only works in some DBMSs (possibly only MySQL).
What i do is add my own sql to do this, after the add_column call, like so:
add_column :students, :foo, :string
ActiveRecord::Base.connection.execute("ALTER table students MODIFY COLUMN foo varchar(255) AFTER name")
Your SQL will need to be DBMS-specific, ie tailored to MySql, PostGresql, SQLite etc.
Well, SQLite does not handle AFTER syntax so in this situation the best solution is leave unchanged order of columns or create new table.