undefined method `<<' for nil:NilClass rails console - ruby-on-rails

Hey i'm creating database schema and test it in rails console. I have relation User has_many :rates and Rates belongs_to :user. When I type in rails console:
user = User.find(1)
rate = Rate.find(1)
user.rates << rate
Every thing works fine, but when i want to do it in opposite way:
user2 = User.find(2)
rate2 = Rate.find(2)
rate2.user << user2
I've got an following error NoMethodError: undefined method `<<' for nil:NilClass
Users Migration
class CreateUsers < ActiveRecord::Migration
def up
create_table :users do |t|
t.column "username", :string, :limit => 25
t.string "first_name", :limit => 30
t.string "last_name", :limit => 50
t.string "password"
t.date "date_of_birth"
t.timestamps
end
end
end
Rates Migration
class CreateRates < ActiveRecord::Migration
def change
create_table :rates do |t|
t.integer "user_id"
t.integer "credibility", :limit => 1 #0 or 1
t.timestamps
end
add_index("rates", "user_id")
end
end

The user attribute is not an array (or collection of any kind), you must assign to it.
user2 = User.find(2)
rate2 = Rate.find(2)
rate2.user = user2

Related

has_one association not adding methods to belongs_to class

I have two tables User and UserToken. User has_one: token and UserToken belongs_to :user. I was under the impression this would add UserToken#User method to the UserToken class. However, I am getting:
undefined method 'user' for '#' with the
following 'UserToken.where(user_id: 1).user
Do I not understand the association correctly or have I not set it up right?
UsersController:
def get
user = UserToken.where(user_id: 1).user
render json: user.to_json
end
User Model:
class User < ApplicationRecord
has_one :user_token
end
UserToken Model:
class UserToken < ApplicationRecord
belongs_to :user
end
Migration:
def change
create_table :users do |t|
# This id comes from Auth0
t.datetime :date
t.timestamp :updated_at
t.timestamp :created_at
end
create_table :user_tokens do |t|
t.belongs_to :user
# This comes from plaid when a user signs in
t.string :token
t.timestamp :updated_at
t.timestamp :created_at
end
end
Schema:
ActiveRecord::Schema.define(version: 2019_09_19_004350) do
create_table "user_tokens", force: :cascade do |t|
t.bigint "user_id"
t.string "token"
t.datetime "updated_at"
t.datetime "created_at"
t.index ["user_id"], name: "index_user_tokens_on_user_id"
end
create_table "users", force: :cascade do |t|
t.datetime "date"
t.datetime "updated_at"
t.datetime "created_at"
end
end
What you want is:
UserToken.where(user_id: 1).first.user
or better yet:
UserToken.find_by(user_id: 1).user
You're getting the "undefined method" error because #where returns an ActiveRecord::Relation and an ActiveRecord Relation has no #user method.
UserToken.where(user_id: 1).class.name
#=> "ActiveRecord::Relation"
UserToken.where(user_id: 1).first.class.name
#=> "UserToken"

NoMethodError (undefined method `each' for "0":String)

Rails 5.1
My migration file:
class CreateFwExports < ActiveRecord::Migration[5.1]
def change
create_table :fw_exports, id: :string do |t|
t.string :screen_name, index: true, limit: 16
t.string :full_name, limit: 21
t.string :location_placeholder
t.timestamps
end
end
end
From the fw_exports controller:
def fw_export_params
params.require(:fw_export).permit(:screen_name, :full_name, :location_placeholder)
end
In the fw_export.rb model, I have:
has_one :location
has_many :followers
In the location.rb model, I have:
belongs_to :fw_export
In the follower.rb model, I have:
has_many :followed
In my helper file, I have the following method:
def process_spreadsheet(number_of_rows, spreadsheet, followed_id)
(1..number_of_rows).each do |i|
fw_export_record = FwExport.new(
:screen_name => spreadsheet[i][0],
:full_name => spreadsheet[i][1],
:location_placeholder => spreadsheet[i][2],
)
fw_export_record.save
location = Location.new(
:fw_exports_id => fw_export_record.id
)
location.save
follower = Follower.new(
:followed_id => followed_id,
:fw_exports_id => fw_export_record.id
)
follower.save
end
end
What this method does, is receive a spreadsheet CSV object, and iterates through the data, trying to save each row to the fw_exports table. It also creates entries into the locations and followers tables
There is a locations table, with the following fields:
t.string :fw_exports_id, index: true
t.string :city
t.string :state
t.string :country
and a followers table with the following fields:
t.string :followed_id
t.string :fw_exports_id
t.string :slug, index: true
When I try to import the data, I get the following error:
NoMethodError (undefined method `each' for "0":String):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'
I verified that all the parameters passed to the process_spreadsheet call are valid.
Any ideas?

Rails 5 returning `#<ActiveRecord::Relation []>`

I am new to trying to understand associations in ActiveRecord and it is currently returning #<ActiveRecord::Relation []> to a query I am running in the Web Console.
In a nutshell, I read the Rails Guides and figured has_and_belongs_to_many was the best solution. My terminal shows it is running the query but it appears to just be returning an empty array and the output is below.
Processing by ScheduleController#show as HTML
Parameters: {"id"=>"1"}
Schedule Load (0.2ms) SELECT "schedules".* FROM "schedules" WHERE "schedules"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Player Load (0.3ms) SELECT "players".* FROM "players" WHERE "players"."team" = ? [["team", "#schedule.home"]]
I have a Schedule and a Players model, the idea is to return a list of players based on home and away team names.
models/player.rb
class Player < ApplicationRecord
has_and_belongs_to_many :schedules
end
models/schedule.rb
class Schedule < ApplicationRecord
has_and_belongs_to_many :players
end
db/migrate/(numbers)_create_schedules.rb
class CreateSchedules < ActiveRecord::Migration[5.0]
def change
create_table :schedules do |t|
t.string :leagueGame
t.string :home
t.string :homeAbr
t.string :away
t.string :awayAbr
t.string :venue
t.string :prettyDate
t.string :homeLogo
t.string :homeLogoLarge
t.string :awayLogo
t.string :awayLogoLarge
t.date :date
t.timestamps
end
create_table :player_schedule do |t|
t.belongs_to :player, index: true
t.belongs_to :schedule, index: true
end
end
end
db/migrate/(numbers)_create_players.rb
class CreatePlayers < ActiveRecord::Migration[5.0]
def change
create_table :players do |t|
t.string :name
t.string :team
t.string :shoots
t.string :catches
t.string :position
t.string :abr
t.integer :number
t.integer :gp
t.integer :goals
t.integer :assists
t.integer :points
t.integer :pim
t.integer :plusMinus
t.decimal :gaa
t.integer :svs
t.timestamps
end
end
end
controllers/schedule_controller.rb
# For brevity
def show
#schedule = Schedule.find(params[:id])
#home_lineup = Player.where(team: '#schedule.home')
end
The #home_lineup is the call returning the empty array. I can call #schedule.home and it displays the correct team name but am I able to call it like I have as part of a table lookup?
Replace
#home_lineup = Player.where(team: '#schedule.home')
with
#home_lineup = Player.where(team: #schedule.home)
As per your code, you are searching for team with name '#schedule.home' instead of the actual team name.

Association problems in between models RAILS 4

My models
CAR BRANDS MODEL
class CarBrand < ActiveRecord::Base
has_many :car_ads
end
CAR ADVERTISEMENTS MODEL
class CarAd < ActiveRecord::Base
has_one :car_brand
end
my controller:
def index
#car_ads = CarAd.all.order("car_ads.created_at DESC")
end
car ads migrations:
class CreateCarAds < ActiveRecord::Migration
def up
create_table :car_ads do |t|
t.integer "user_id"
t.integer "car_brand_id"
t.integer "car_model_id"
t.integer "state_id", :limit => 2
t.integer "vin_id"
t.integer "year_manufac", :precision => 4
t.integer "km_age"
t.integer "price_usd", :limit => 7
t.integer "car_tel_number", :precision => 8
t.float "motor_volume", :limit => 10
t.string "transmission"
t.integer "horse_power", :limit => 3
t.text "description"
t.boolean "visible", :default => true
t.boolean "active", :default => true
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
t.timestamps null: false
end
add_index :car_ads, :user_id
add_index :car_ads, :car_brand_id
add_index :car_ads, :car_model_id
add_index :car_ads, :state_id
add_index :car_ads, :vin_id
end
def down
drop_table :car_ads
end
end
Car brands migratiions
class CreateCarBrands < ActiveRecord::Migration
def up
create_table :car_brands do |t|
t.string "brand", :limit => 20
t.timestamps null: false
end
end
def down
drop_table :car_brands
end
end
so the problem is that i cant get car brand form car ads, please help,
i wanted to get that like
iterating
<% #car_ads.each do |carad|%>
<%= carad.car_brand %>
<%end%>
Modify CAR ADVERTISEMENTS MODEL
class CarAd < ActiveRecord::Base
belongs_to :car_brand
end
Modify your controller:
def index
#car_ads = CarAd.all.order("created_at DESC")
end
You didn't add any reference to CarBrand in CarAd table, just add the car_ad_id column with a migration like this
class AddCarBradIdToCarAd < ActiveRecord::Migration
def change
add_column :car_ads, :car_brand_id, :integer
end
end
So rails would be able to get the corresponding CarBrand from a CarAd

Can't access related table

I am really under pressure and totally new to Rails. Project due in two days.
I have done a search on Rails console for a user inputted in my database user = user.find(1) and it returns.
the user has_many recipes
recipes belongs to user ....defined in user and recipe models respectively.
I am getting the error.
undefined method "recipe" for user?
This is how I created my User
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.integer "position"
t.boolean "visible", :default => false
t.string "restaurant_name", :limit => 25
t.string "username", :limit => 25
t.string "password", :limit => 50
t.string "hashed_email", :default => "", :null => false
t.string "address1", :limit => 80
t.string "address2", :limit => 80
t.string "address3", :limit => 80
t.string "county", :limit => 40
t.string "telephone", :limit => 40
t.text "web address", :limit => 60
t.string "photo_path", :limit => 100
t.text "description", :limit => 2000
t.text "salt", :string, :limit => 50
t.timestamps
end
end
def self.down
drop_table :users
end
end
Recipe
class CreateRecipes < ActiveRecord::Migration
def self.up
create_table :recipes do |t|
t.integer "user_id"
t.string "recipe_name", :limit => 100
t.integer "greedy_type", :default => 0
t.string "photo_path", :limit => 40
t.text "description", :limit => 400
t.text "recipe", :limit => 4000
t.integer "ingredient1", :limit => 40
t.integer "ingredient2", :limit => 40
t.integer "ingredient3", :limit => 40
t.integer "ingredient4", :limit => 40
t.string "permalink"
t.integer "position"
t.boolean "visible", :default => false
t.timestamps
end
add_index("recipes", "user_id")
add_index("recipes", "permalink")
end
def self.down
drop_table :recipes
end
end
users.rb
class Users < ActiveRecord::Base
has_many :recipes
end
recipe.rb
class Recipes < ActiveRecord::Base
belongs_to :users
has_many :restaurants
end
ERROR
irb(main):005:0> users.recipe
NoMethodError: undefined method `recipe' for #<Users:0x599ebc0>
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activemodel-3.0.9/lib/active_model/attribute_methods.rb:
392:in `method_missing'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activerecord-3.0.9/lib/active_record/attribute_methods.r
b:46:in `method_missing'
If User has_many recipes, why you add field recipe_id for user? You should add user_id field to the Recipe class table. After creating recipe just store user_id and that is all you need. Cheers!
as user has many recipes,
you have to write something like to get first users recipe..
recipe = user.recipes.first
and store user_id in recipe table.

Resources