Rails Model.create SQLite3::SQLException - ruby-on-rails

I'm a beginner in Rails, and I'm having trouble inserting rows into the database using Rails's migration.
class Actions < ActiveRecord::Migration
def up
create_table :actions do |t|
t.integer :channel_id
t.string :name
t.text :description
t.integer :weight
t.timestamps
end
add_index :actions, :channel_id
Actions.create :name => 'name', :description => '', :weight => 1, :channel_id => 1
end
Running this code results in:
== Actions: migrating ========================================================
-- create_table(:actions)
-> 0.0076s
-- add_index(:actions, :channel_id)
-> 0.0036s
-- create({:name=>"name", :description=>"", :weight=>1, :channel_id=>1})
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: unrecognized token: "{": {:name=>"name", :description=>"", :weight=>1, :channel_id=>1}
The Action model:
class Actions < ActiveRecord::Base
belongs_to :channels
attr_accessible :name, :description, :weight, :channel_id
end
I don't know where the curly brackets come from and why they cause an exception. Who can help me solving this problem?

Uh oh, it seems that your migration class name is the same as the name of the model you're trying to access (Actions). Because of this, instead of the model class, the create method will be called on the migration class, which probably tries to create a table using your hash, or something. That's why you're getting that error message.
Rename your migration class (and also its file for the sake of consistency) and it should run fine:
class CreateActions < ActiveRecord::Migration

Related

Unknown attribute despite having initialized it

I am completely new to rails and I ran into a problem while I try to define an association between models. To be specific, I am trying to create a relationship between task and category but It ran into the error when I try to connect them category.tasks << task1.
The Error:
C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/activemodel-7.0.4/lib/active_model/attribute.rb:211:in `with_value_from_database': can't write unknown attribute `category_id` (ActiveModel::MissingAttributeError)
raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{name}`"
^^^^^
task1 attribute:
t.string :name
t.text :description
t.integer :position
t.boolean :completed
t.timestamps
category attribute:
t.string :name
t.timestamps
the pre-set the connection between task and catogory
class AddCategoryIdtoTask < ActiveRecord::Migration[7.0]
def change
add_column(:tasks, :category_id, :integer, index:true)
end
end
class Task < ApplicationRecord
belongs_to :category, optional: true
end
class Category < ApplicationRecord
has_many :tasks
end
When I appendix task1 into category.tasks , would it not update the category_id to match?
I hope some passerby could look into this error that I feel like I am obviously missing something

NoMethodError: undefined method `title' for #<Ingredient:0x0000000005e6cf30>

I have come across this error a few times this week, but this time I have no idea what is wrong. I have an ActiveRecord Model called Ingredients
class CreateIngredients < ActiveRecord::Migration[5.2]
def change
create_table :ingredients do |t|
t.string :title , null: false
t.integer :availability
t.decimal :price, precision:15, scale: 2
t.timestamps
end
end
end
And this is the application record I have for it:
class Ingredient < ApplicationRecord
validates :title, presence: true
has_many :ingredient_categories
has_many :categories, through: :ingredient_categories
end
Now I try to create a new Ingredient on the irb but I get an error saying:
NoMethodError: undefined method 'title' for #Ingredient:0x0000000005e6cf30>
This is the exact output on the console:
irb(main):003:0> Ingredient.create!(title: 'Cheese Spread')
#=> ActiveModel::UnknownAttributeError: unknown attribute 'title' for Ingredient.
Can someone help me understand what I am doing wrong?
Try rails db:migrate if you have not added this migration and then use rails console.
What you probably did was rails db:migrate when you first created the table, but after you added the columns you did not and so when you went to create an Ingredient, it knew what the table was, thus why it could not go further than title.

Postgresql error when reverse geocoding in Ruby on Rails

I am having an issue trying to do a bulk reverse geocode using the geocoder rails gem: https://github.com/alexreisner/geocoder
I have the following models:
class School < ActiveRecord::Base
reverse_geocoded_by :latitude, :longitude
has_one :address
end
and
class Address < ActiveRecord::Base
belongs_to :school
end
And the following migrations:
class CreateSchools < ActiveRecord::Migration
def change
create_table :schools do |t|
t.string :name
t.integer :address_id
t.timestamps null: false
end
end
end
and
class CreateAddresses < ActiveRecord::Migration
def change
create_table :addresses do |t|
t.string :line_1
t.string :line_2
t.string :line_3
t.string :city
t.string :region
t.string :country
t.string :code
t.timestamps null: false
end
end
end
and when I run the following line:
rake geocode:all CLASS=School REVERSE=true SLEEP=0.5
I get this error:
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column schools.address does not exist
LINE 1: SELECT "schools".* FROM "schools" WHERE (schools.address IS...
^
: SELECT "schools".* FROM "schools" WHERE (schools.address IS NULL) ORDER BY "schools"."id" ASC LIMIT 1000
I know the readme says this:
"For geocoding your model must provide a method that returns an
address. This can be a single attribute, but it can also be a method
that returns a string assembled from different attributes (eg: city,
state, and country)."
I took that to mean I needed either a method on the School model or the attribute on the school table and I opted for the latter but I'm not sure what I'm missing.
Thanks!
The problem is that the reverse-geocoding rake task starts by loading all the records with no address column yet. It uses this scope:
scope :not_reverse_geocoded, lambda {
where("#{table_name}.#{geocoder_options[:fetched_address]} IS NULL")
}
The problem is you don't have any column on schools you could use. Instead, you should move the reverse_geocoded_by declaration to the Address class. You will also need to either add an addresses.address column or do something like this:
reverse_geocoded_by :latitude, :longitude, fetched_address: :line_1
Also you don't seem to have columns for latitude and longitude. And of course those should be on Address too, not School. After all, if a school can have several addresses, which one is its lonlat?

ruby on rails. seed error while creating objects with association

I am trying to create a task management prototype. I created two models - Category and Task, while tasks belong to category and a category can contain many tasks.
class Category < ActiveRecord::Base
has_many :tasks
end
And
class Task < ActiveRecord::Base
belongs_to :category
end
Then in migration file
class CreateTasks < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.string :name
t.string :note
t.references :category
t.timestamps null: false
end
end
end
and
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.string :description
t.timestamps null: false
end
end
end
I tried to seed some data to start working with, here's the seed file
c1 = Category.create(name: 'Category1')
Task.create(name: 'TASK1', category_id: c1.id)
However it gives me the error:
rake db:seed
rake aborted!
ActiveRecord::UnknownAttributeError: unknown attribute 'category_id' for Task.
I have tried the following as well
Task.create(name: 'TASK1', category: c1)
Task.create(name: 'TASK1', category: c1.id)
And I got the error
rake db:seed
rake aborted!
ActiveRecord::AssociationTypeMismatch: Category(#70174570341620) expected, got Fixnum(#70174565126780)
However in the browser, #category.id does load and display (as a two digit number 33).
Think I might be missing something obvious but can't figure out why I can't create the task associated with the specific category c1 in from the seeding the data
just need to pass the object:
c1 = Category.find_or_create_by(name: 'Category1')
I recommend to use find_or_create_by for not create twice the same data
Task.find_or_create_by(name: 'TASK1', category: c1)
if not work try create the same data in the console
I hope help you

Plural to Singular conversion trouble in Rails Migrations?

I'm a beginner at Ruby On Rails and am trying to get a migration to work with the name Priorities
So, here is the code I use in my migration:
class Priorities < ActiveRecord::Migration
def self.up
create_table :priorities do |t|
t.column :name, :string, :null => false, :limit => 32
end
Priority.create :name => "Critical"
Priority.create :name => "Major"
Priority.create :name => "Minor"
end
def self.down
drop_table :priorities
end
end
This results in the following error though:
NOTICE: CREATE TABLE will create implicit sequence "priorities_id_seq" for serial column "priorities.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "priorities_pkey" for table "priorities"
rake aborted!
An error has occurred, this and all later migrations canceled:
uninitialized constant Priorities::Priority
Is this some problem with turning ies to y for converting something plural to singular?
Also, the full --trace log is here: http://pastebin.com/w6usBSng
Using the following command, I was able to get the same error:
script/generate migration priorities
This is happening because you don't have a Priority class. You probably intended on running this command:
script/generate model Priority name:string
This fixes the problem
EDIT
Apparently you don't want a Priority model. In this situation, I have no idea why, but you can circumvent this by using execute in your migration methods.
Try something like this:
class CreatePriorities < ActiveRecord::Migration
def self.up
create_table :priorities do |t|
t.column :name, :string, :null => false, :limit => 32
end
execute "insert into priorities (name) values ('Critical');"
execute "insert into priorities (name) values ('Major');"
execute "insert into priorities (name) values ('Minor');"
end
def self.down
drop_table :priorities
end
en
d
Yes. Your table name is Priorities and Model name also (i guess) Priorities. So it get crashed at "Priority.create :name => "Critical".
This should be
class Priorities < ActiveRecord::Migration
def self.up
create_table :priorities do |t|
t.column :name, :string, :null => false, :limit => 32
end
Priorities.create :name => "Critical" #Where "Priorities" is your Model Name
Priorities.create :name => "Major"
Priorities.create :name => "Minor"
end
def self.down
drop_table :priorities
end
end

Resources