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.
Related
I am trying to query the following
Vehicle.where(:account.name => "").count
and I get this error:
NoMethodError: undefined method `name' for :account:Symbol
The associations between Vehicle and Account have been define on the model, and I user conventions. Why do I get this error?
Vehicle.rb
class Vehicle < ActiveRecord::Base
belongs_to :account
end
Account.rb
class Account < ActiveRecord::Base
has_many :vehicles
end
Schema
create_table "accounts", force: true do |t|
t.string "name"
...
end
create_table "vehicles", force: true do |t|
t.integer "account_id"
...
end
You can use the following:
Vehicle.joins(:account).where("accounts.name = ?", "").count
You can also search for blank fields with:
Vehicle.joins(:account).where("accounts.name <> ''").count
Error is raise because rails is considering account as a column, if you want to where condition for associated table then make join between them, like following
Vehicle.joins('account').where("account.name IS NULL").count
I am trying to make a RoR project and I am currently have issues with Model Association. This is probably caused by an error or misunderstanding but in the last 2 days I have not been able to find this error or misunderstanding.
I want the associations to work like this:
User
=> gapiToken
=> userSession
So that technically I could just call User.find(foo).gapiToken.
Currently I have it setup so
User
has_many :userSessions
has_one :gapiToken
UserSession
belongs_to :user
GapiToken
belongs_to :user
However for some reason this does not seam to be working.
For example, this piece of code:
#user = User.create(gid: foo, permissions: bar)
#gapiToken = #user.gapiToken.create(access_token: foo, token_type: bar, expires_on: bazz, refresh_token: bop)
#^ Error ^ "undefined method `create' for nil:NilClass"
Am I going about this wrong in the usage or in the setup, or both?
Complete code
First, be sure to follow conventions. Use under_scores, not camelCase:
User
has_many :user_sessions
has_one :gapi_token
Second, the method #model_instance.association.create is for one-to-many associations, not one-to-one associations. It should be:
#user.create_gapi_token(...)
See here for more information about the associations API.
A note on YOUR CODE
Don't forget indexes.
A basic rule of thumb: index foreign keys, and index both keys on a join table. Example:
create_table :user_sessions do |t|
t.belongs_to :user # will result in t.integer :user_id
end
add_index :user_sessions, :user_id
create_table :gapi_tokens, id: false do |t|
t.belongs_to :user
end
add_index :gapi_tokens, :user_id
Example of an index on a join table (note id: false and unique: true):
create_table :users_favourites, id: false do |t|
t.belongs_to :user
t.belongs_to :favourite
end
add_index :users_favourites, [:user_id, :favourite_id], unique: true
Read about migrations, then read and re-read the Rails guides.
It's important you understand the conventions so you don't shoot yourself in the foot later down the road.
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
Please help with ActiveRecord testing. Trying my first Rails 3.1.0 project. There I have model named "Account", described like:
migration.rb:
def self.up
create_table :accounts do |t|
t.string :name
t.integer :type
t.references :user
t.timestamps
end
add_index :accounts, :user_id
end
account_model.rb
class Account < ActiveRecord::Base
belongs_to :user
validates_length_of :name, :within => 15..255
validates_numericality_of :type
end
And if i'm making in Rspec :
account = Account.new(:type => 1)
account.type.should == 1
I've got test result:
Failure/Error: account.type.should == 1
expected: 1
got: nil (using ==)
I tried Account creation in console, and every time i'm assigning any integer value as 'type', i got 'nil'. Not assigned value. What I'm making wrong?
'type' is a protected attribute in rails, because .type is a ruby method. Hence you can't mass assign it. Rename the attribute (eg :account_type) & everything should work fine.
I've been trying to setup a Single Table Inheritance model in Rails 3 in which the parent class also contains a has_many relationship. Unfortunately I can't get it to work. Here are three classes as an example:
class Article < ActiveRecord::Base
has_many :paragraphs, :dependent => :destroy, :autosave => true
end
class Paragraph < ActiveRecord::Base
belongs_to :article
end
class SportsArticle < Article
end
And here's the migration that would be used to set this up:
class AddTables < ActiveRecord::Migration
def self.up
create_table :articles do |t|
t.string :type, :null => false # for STI
t.string :title, :null => false
t.timestamps
end
create_table :paragraphs do |t|
t.references :article, :null => false
t.timestamps
end
end
def self.down
drop_table :articles
drop_table :paragraphs
end
end
When I set it up this way and I try to create a new SportsArticle, say by doing the following:
SportsArticle.create(:title => "Go Giants")
I always get the following error:
"TypeError: can't convert String into Integer"
I have no idea how to fix this issue and have tried finding a solution online to no avail. Does anybody who has experience with STI models see anything wrong? Here's the link to the documentation on the create method if it will help in diagnosing the problem:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-create
Try renaming :type to something else, like :article_type
eg:
t.string :article_type, :null => false # for STI
The error was being caused due to a naming collision. I was using a name for one of my models called "attributes" which was causing the problem. The hint that eventually diagnosed the problem came from the Rails Association Documentation.