While I'm trying to setup friendly_id to my rails4 project, similarly, I got error after I add "friend" after "friend" to friends table. How can I fix it:
PG::UniqueViolation - ERROR: duplicate key value violates unique constraint "index_friends_on_slug"
DETAIL: Key (slug)=() already exists.
In addition, here are my files the issue may be based on:
# app/models/friend.rb:
class Friend < ActiveRecord::Base
has_many :entries, dependent: :destroy
belongs_to :user
extend FriendlyId
friendly_id :candidates, use: [:slugged, :finders] # not :history here
def candidates
[
:first_name,
[:first_name, :last_name]
]
end
end
# db/schema.rb:
create_table "friends", force: true do |t|
t.string "first_name"
t.string "last_name"
t.text "address"
t.string "email"
t.string "phone"
t.string "slug"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "friends", ["slug"], name: "index_friends_on_slug", unique: true, using: :btree
add_index "friends", ["user_id"], name: "index_friends_on_user_id", using: :btree
UPDATE: migration file:
class CreateFriends < ActiveRecord::Migration
def change
create_table :friends do |t|
t.string :first_name
t.string :last_name
t.text :address
t.string :email
t.string :phone
t.string :slug
t.integer :user_id
t.timestamps
end
add_index :friends, :slug, unique: true
add_index :friends, :user_id
end
end
Now fixed by uncommenting these lines on config/initializers/friendly_id.rb:
# Most applications will use the :slugged module everywhere. If you wish
# to do so, uncomment the following line.
#
config.use :slugged, :finders
#
# By default, FriendlyId's :slugged addon expects the slug column to be named
# 'slug', but you can change it if you wish.
#
config.slug_column = 'slug'
Thanks #basgys, #DavidGrayson and rest of us...
The error makes it sound like two rows in the database share the same slug, which is just empty string, and that is not allowed because you are adding a unique index on the slug column.
When does the error actually happen? What keystroke or click causes it?
Either delete the rows in the friends table or make the index non-unique by removing that option from the migration file (you can change it later with another migration).
Related
I have a User model with uuid for id column.
Ahoy gem creates visits as expected but the user_id is wrong.
Any ideas?
ok. Got that. Ahoy gem doesn't work with user_id as UUID. It takes the first digits from uuid and stores that in user_id for Ahoy::Visit which could look like random value.
The solution is to change the user_id type to uuid.
This migration would do the trick:
class ChangeAhoyVisits < ActiveRecord::Migration[5.2]
def change
Ahoy::Visit.destroy_all
remove_column :ahoy_visits, :user_id, :bigint
add_column :ahoy_visits, :user_id, :uuid, foreign_key: true, null: true
add_index :ahoy_visits, :user_id
end
end
Probably need to add the same type: :uuid to the user_id column in the ahoy_events table as well. After a few rake db:rollback's I ended up modifying the original migration file that is created by rails generate ahoy:install to look like this before I ran the migration:
def change
create_table :ahoy_visits do |t|
t.string :visit_token
t.string :visitor_token
# the rest are recommended but optional
# simply remove any you don't want
# user
t.references :user, type: :uuid, foreign_key: true, index: true
# standard
t.string :ip
t.text :user_agent
t.text :referrer
t.string :referring_domain
t.text :landing_page
# technology
t.string :browser
t.string :os
t.string :device_type
# location
t.string :country
t.string :region
t.string :city
t.float :latitude
t.float :longitude
# utm parameters
t.string :utm_source
t.string :utm_medium
t.string :utm_term
t.string :utm_content
t.string :utm_campaign
# native apps
t.string :app_version
t.string :os_version
t.string :platform
t.datetime :started_at
end
add_index :ahoy_visits, :visit_token, unique: true
create_table :ahoy_events do |t|
t.references :visit
t.references :user, type: :uuid, foreign_key: true, index: true
t.string :name
t.jsonb :properties
t.datetime :time
end
add_index :ahoy_events, [:name, :time]
add_index :ahoy_events, :properties, using: :gin, opclass: :jsonb_path_ops
end
And after running this slightly modified migration rather than original everything seemed to populate properly on an 'ahoy.track' in the db.
In my Rails project with a Postgres database, I have a user and workspace model. They are associated by a many to many relationship (users_workspaces). If I open up my rails console and try to get all user workspaces with UserWorkspace.all, I get the following 'relation does not exist' error:
2.5.1 :001 > UserWorkspace.all
Traceback (most recent call last):
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: relation "user_workspaces" does not exist)
LINE 1: SELECT "user_workspaces".* FROM "user_workspaces" LIMIT $1
^
: SELECT "user_workspaces".* FROM "user_workspaces" LIMIT $1
2.5.1 :002 >
I don't understand why it's looking for user_workspaces (user being singular) rather than users_workspaces (both names plural). I'll looked through my codebase to see if this is in fact set somewhere as user_workspaces, but can't find it. I've also run rails db:drop db:create db:migrate, but still no luck. Here are related files, but I'm not sure where is issue is originating from.
user model
class User < ApplicationRecord
has_secure_password
has_and_belongs_to_many :workspaces
validates_presence_of :username, :email, :password, :subscription_plan
validates_uniqueness_of :username, :email
validates_length_of :username, :within => 3..40
validates_length_of :password, :within => 8..100
end
workspace model
class Workspace < ApplicationRecord
has_and_belongs_to_many :users
validates_presence_of :name
validates_presence_of :admin_id
end
user_workspace model
class UserWorkspace < ApplicationRecord
belongs_to :user
belongs_to :workspace
validates_presence_of :user, :workspace
end
schema.rb
ActiveRecord::Schema.define(version: 2018_07_28_040836) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "users", force: :cascade do |t|
t.string "username", null: false
t.string "email", null: false
t.string "first_name"
t.string "last_name"
t.string "password_digest"
t.integer "subscription_plan", default: 0, null: false
t.integer "current_workspace"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["username"], name: "index_users_on_username", unique: true
end
create_table "users_workspaces", id: false, force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "workspace_id", null: false
t.index ["user_id", "workspace_id"], name: "index_users_workspaces_on_user_id_and_workspace_id"
t.index ["workspace_id", "user_id"], name: "index_users_workspaces_on_workspace_id_and_user_id"
end
create_table "workspaces", force: :cascade do |t|
t.string "name", null: false
t.text "description"
t.integer "admin_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
users migrations
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :username, null: false, index: {unique: true}
t.string :email, null: false, unique: true
t.string :first_name
t.string :last_name
t.string :password_digest
t.integer :subscription_plan, null: false, default: 0
t.integer :current_workspace
t.timestamps
end
end
end
workspaces migration
class CreateWorkspaces < ActiveRecord::Migration[5.2]
def change
create_table :workspaces do |t|
t.string :name, null: false
t.text :description
t.integer :admin_id
t.timestamps
end
end
end
users_workspaces (join table) migration file
class CreateJoinTableUsersWorkspaces < ActiveRecord::Migration[5.2]
def change
create_join_table :users, :workspaces do |t|
t.index [:user_id, :workspace_id]
t.index [:workspace_id, :user_id]
end
end
end
Any and all help would be greatly appreciated. Thanks!
As mentioned in schema.rb table is created by the name users_workspaces and your class name is UserWorkspaces.
By default, rails try to infer the table name for a Model by its class name.
So, If classname is UserWorkspace then its corresponding table_name will be user_workspaces and not users_workspaces.
Now, You have two options either rename your model or somehow mention in your model that the table you want to use for this model.
Option-1
Rename Model
class UsersWorkspace < ApplicationRecord
belongs_to :user
belongs_to :workspace
validates_presence_of :user, :workspace
end
Option-2
Allow UserWorkspace model to point to users_workspaces table
class UserWorkspace < ApplicationRecord
self.table_name = 'users_workspaces'
belongs_to :user
belongs_to :workspace
validates_presence_of :user, :workspace
end
UPDATE
In addition to above in UserWorkspace/UsersWorkspace Model you don't need
validates_presence_of :user, :workspace
as since you are using rails 5.2, therefore, rails itself adds presence validation along with belongs_to association unless you have pass optional: true argument or you have declared it in the following way in application.rb
Rails.application.config.active_record.belongs_to_required_by_default = false
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 want each student to be able to post multiple messages on my site.
therefore each student has_many :posts
and a post belongs_to :student (one student only)
The thing is I can create a record for a student in rails console but can't assign a post to the student ? I am a bit confused. The student model with the has many does not have the attributes from the belongs to model ?
I have a student.rb model
class Student < ActiveRecord::Base
attr_accessible :first_name, :last_name, :email, :gender, :number, :college, :password, :budget, :picture
mount_uploader :picture, PictureUploader
has_many :posts
end
I have a post.rb model
class Post < ActiveRecord::Base
attr_accessible :message
belongs_to :student
end
this is my schema
ActiveRecord::Schema.define(version: 20130827191617) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "posts", force: true do |t|
t.text "message"
end
create_table "students", force: true do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "number"
t.string "college"
t.string "password"
t.float "budget"
t.string "picture"
t.datetime "created_at"
t.datetime "updated_at"
end
You should add student_id integer column (it would be better if there was also index on this column) to posts table.
To do this, you can type in console:
bundle exec rails g migration add_student_id_to_posts student:references
How can I set primary key for my IdClient field? I have tried all methods, but I'll get errors (rails 3.0.9)... Could you help me?
class CreateCustomers < ActiveRecord::Migration
def self.up
create_table :customers do |t|
t.integer :IdCustomer
t.string :username
t.string :crypted_password
t.string :password_salt
t.string :persistence_token
t.string :email
t.string :Skype
t.string :ICQ
t.string :Firstname
t.string :Lastname
t.string :Country
t.string :State
t.string :City
t.string :Street
t.string :Building
t.integer :Room
t.string :AddressNote
t.date :DateOfReg
t.integer :CustGroup
t.float :TotalBuy
t.timestamps
add_index(:customers, :IdCustomer, :unique => true)
end
end
def self.down
drop_table :customers
end
end
Also how to set relations in model?
Don't do this. Use the built-in id field as the primary key. If you're going to use Rails, you should build your app the "Rails way" unless you have very good reason not to.
If you really want to do this, you can pass a :primary_key option to create_table:
create_table :customers, :primary_key => :idClient do |t|
# ...
end
You'll also need to tell your model the name of its primary key via self.primary_key = "idClient"