My data is not being seeded ruby on rails - ruby-on-rails

I have a rails application.I have added some sample data to seeds.rb file.After i ran rails db:seed ,I checked in my rails c to see if everything was sucessful. I was able to get all the restaurants using the command Restaurant.all......but for users,reservation and every thing else im getting an ampty array.
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
#User
hannah=User.create(name:"Hannah",email:"hannah#gmail.com")
joe=User.create(name:"Joe",email:"joe#gmail.com")
selena=User.create(name:"Selena",email:"selena#gmail.com")
puts "Done user"
#Restaurant
daniel=Restaurant.create(name: "Daniel",cuisine: "French Restaurant",cost: "$$$$",address: "60 E 65th St, New York, NY 10065, United States",hours: "5-9:45pm",closed:"Monday closed",phone: "+(1) 212-288-0033",must_try:"Soupe à l’oignon,Chocolate soufflé,Coq au vin",category:"alc",website:"https://www.danielnyc.com/",image:"https://cdn.vox-cdn.com/thumbor/sD1NYldxSFfdF0eGZItfYHK3vAE=/1400x1050/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/21917204/RD_MDR_FrancescoTonelli1.jpg")
ksh=Restaurant.create(name:"COTE Korean Steakhouse",cuisine:"Steak House",cost: "$$$$",address: "16 W 22nd St, New York, NY 10010, United States",hours: "5-11pm",closed:"Open all days",phone: "+1 212-401-7986",must_try: "Beef Manhattan,Pot Roast",category:"alc",website:"https://www.cotenyc.com/",image:"https://i.pinimg.com/originals/76/38/26/763826ba948e44274b2194a02228eeba.jpg")
sn=Restaurant.create(name:"Sushi Nakazawa",cuisine:"Sushi Restaurant",cost: "$$$",address:"23 Commerce St, New York, NY 10014, United States",hours: "11:30am-2pm & 5pm-10:30pm",closed: "Open all days",phone: "+1 212-924-2212",must_try: "King Crab Roll ,Boston Roll,Rainbow Roll",category:"alc",website:"https://www.sushinakazawa.com/",image:"https://nypost.com/wp-content/uploads/sites/2/2014/02/sushi.jpg?quality=75&strip=all")
cir=Restaurant.create(name:"Carmine's Italian Restaurant - Times Square",cost:"$$",address:"200 W 44th St, New York, NY 10036, United States",hours: "11:30am-11-pm",closed:"Open all days",phone:"+1 212-221-3800",must_try:"Spaghetti carbonara, Fritto Misto,Pesto Pizza",category:"alc",website:"https://www.carminesnyc.com/",image:"https://cdn.vox-cdn.com/thumbor/bigr3rAWckq1s4ybdhYFq0GO13Q=/0x0:967x678/1200x800/filters:focal(407x262:561x416)/cdn.vox-cdn.com/uploads/chorus_image/image/69883137/Screen_Shot_2021_09_20_at_11.30.30_AM.0.png")
ci=Restaurant.create(name:"Café Integral",cuisine:"Cafe",cost:"$",address:"149 Elizabeth St, New York, NY 10012, United States",hours:"8am-6:30pm",closed:"Open all days",phone:"+1 212-221-3813",must_try:"S'mores,New York cheesecake,Hot Chocolate",category:"coffeeshop",website:"https://www.cafeintegral.com/",image:"https://sprudge.com/wp-content/uploads/2016/10/NYC_Cafe_Integral_Kat_Odell_LC_Photos-5-740x494.jpg")
fr=Restaurant.create(name:"Felix Roasting Co.",cuisine:"Cafe",cost:"$",address:"450 Park Ave S, New York, NY 10016, United States",hours:"8am -5pm",closed:"Saturdays closed",phone:"+1 212-401-7985",must_try:"Lemon meringue pie,Coconut Yogurt cake,English Breakfast Tea",category:"coffeeshop",website:"https://felixroastingco.com/",image:"https://yorkavenueblog.com/wp-content/uploads/2019/05/Felix-Roasting-Co.-NYC-7698.jpg")
blmwc=Restaurant.create(name:"Bluestone Lane Manhattan West Café",cuisine:"Cafe",cost:"$$",address:"435 W 31st St, New York, NY 10001, United States",hours:"7am-4pm",closed:"Saturday & Sunday 7:30am-4pm",phone:"+1 212-401-1246",must_try:"Matcha Cheesecake,Caramel Vanilla coffee",category:"coffeeshop",website:"https://bluestonelane.com/cafes/manhattan-west-435-w31st-st-new-york/?y_source=1_ODc5Mjg5MS03MTUtbG9jYXRpb24ud2Vic2l0ZQ%3D%3D",image:"https://bluestonelane.com/wp-content/uploads/2017/09/DSC6627-1280x854.jpg")
uqc=Restaurant.create(name:"Union Square Cafe",cuisine:"Cafe",cost:"$$",address:"101 E 19th St, New York, NY 10003, United States",hours:"10am-10:pm",closed:"Wednesday closed",phone:"+1 212-243-4020",must_try:" Chicken fried steak,HotDog,Mac and Cheese",category:"coffeeshop",website:"https://www.unionsquarecafe.com/",image:"https://media.vanityfair.com/photos/586ff60d6cbc6a28245ef9a6/7:3/w_1994,h_854,c_limit/union-square-cafe-danny-meyers.jpg")
act=Restaurant.create(name:"Apotheke Chinatown",cuisine:"Sichuhan,Cocktail Bar",cost:"$$$",address:" 9 Doyers St, New York, NY 10013, United States",hours:"6:30pm -2am",closed:"Tuesday closed",phone:"+1 212-406-0400",must_try:"Spicy Prawn Dumpling,Kung Pao Squids,Chicken and Coriander Dumplings,Blue Jacket,White Lady",category:"bar",website:"https://www.apothekemixology.com/",image:"https://i.pinimg.com/originals/67/a4/52/67a452db69553966eb597ad476b439f7.jpg")
royalty=Restaurant.create(name:"The Royalton Park Ave Rooftop Lounge & Pool",cuisine:"American",cost:"$$$$",address:" 420 Park Ave S, New York, NY 10016, United States",hours:"7pm-3am",closed:"Monday-Thursday",phone:"+1 212-602-3202",must_try:"Caipirinha with Candy Floss,The Midnight Mary",category:"bar",website:"https://www.royaltonparkavenue.com/eat-and-drink/",image:"https://imgcy.trivago.com/c_limit,d_dummy.jpeg,f_auto,h_1300,q_auto,w_2000/itemimages/14/36/1436082_v7.jpeg")
#puts "Done res"
#Review
Review.create(img:"https://cdn.apartmenttherapy.info/image/upload/f_jpg,q_auto:eco,c_fill,g_auto,w_1500,ar_1:1/k%2Farchive%2Fc54907276a7cb6e0545ae2128bdc984e86b6cb9d",r:"Loved the alfredo chicken pasta.The chicken was roasted to perfection.Rose Wine along with just made it better.",restaurant_id:daniel.id,user_id: hannah.id)
Review.create(img:"https://tmbidigitalassetsazure.blob.core.windows.net/rms3-prod/attachments/37/1200x1200/Italian-Hot-Dish_EXPS_HCK19_31288_B08_24_2b.jpg",r:"The cheddar in Arabiatta mushrrom lasagne was just heaven. Do try some amazing macroons",restaurant_id:daniel.id,user_id:joe.id)
Review.create(img:"https://static.toiimg.com/photo/88489342.cms",r:"Felt like I was in Seoul.The food was just fabulous.Thanks to Justin for the good service.",restaurant_id: ksh.id,user_id: selena.id)
puts "Done review"
#Reservations
Reservation.create(name:"Hannah & Joe", date:"30/09/2022",time:"1pm",num:2,contact:123456789,occasion:"Anniversary Party",restaurant_id:ksh.id,user_id:joe.id)
puts "Done reser"
puts "Done seeding"
When I ran Reservation.all I got this
Reservation.all
Reservation Load (1.7ms) SELECT "reservations".* FROM "reservations" /* loading for inspect */ LIMIT $1 [["LIMIT", 11]]
=> #<ActiveRecord::Relation []>

I often create seeds like this. You can refer
Step 1: In seeds.rb
# Users
[
{id: 1, email: "admin#gmail.com", password: "password", name: "Admin"},
{id: 2, email: "user#gmail.com", password: "password", name: "User"},
{id: 3, email: "client#gmail.com", password: "password", name: "Client"},
].each do |attr|
user = User.find_by(id: attr[:id])
User.transaction do
unless user
user = User.new(attr)
user.save
else
user.update_attributes attr
end
end
end
Step 2: Run rails db:seed
Step 3: Open terminal rails c and User.all

Related

How can I create new book and assign two authors with it using Rails miniTest?

Doing TDD
I facing a problem creating a book and assigning two authors with it. There is a failure in the creation. It says that there is an AssociationTypeMismatch: Author(#15100) expected, got nil which is an instance of NilClass(#40. I suppose that the format "authors: []" is not have been read well by something.
This is the test:
def test_has_many_and_belongs_to_mapping
apress = Publisher.find_by(name: 'Apress')
assert_equal 2, apress.books.size
book = Book.new(
title: 'Rails E-Commerce 3nd Edition',
authors: [
Author.find_by(first_name: 'Christian', last_name: 'Hellsten'),
Author.find_by(first_name: 'Jarkko', last_name: 'Laine')
],
published_at: Time.now,
isbn: '123-123-123-x',
blurb: 'E-Commerce on Rails',
page_count: 300,
price: 30.5
)
# apress.books << book
# apress.reload
# book.reload
# assert_equal 3, apress.books.size
# assert_equal 'Apress', book.publisher.name
end
This is the error:
MY ERD:
My schema:
I think what you are missing is a meaningful setup of data needed before this test runs. Even though those publishers and books may exist in your development environment/database, the test suite usually is configured to wipe the database clean between runs.
If you have fixtures defined, then you can reference them like this:
test/fixtures/publishers.yml
apress:
id: 1
name: Apress
test/fixtures/authors.yml
hellsten:
id: 1
first_name: Christian
last_name: Hellsten
laine:
id: 2
first_name: Jarkko
last_name: Laine
test/fixtures/books.yml
beginning_ruby:
title: Beginning Ruby
publisher_id: 1
ruby_recipes:
title: Ruby Recipes
publisher_id: 1
So that the test would look more like this:
def test_has_many_and_belongs_to_mapping
apress = publishers(:apress)
assert_equal 2, apress.books.size
book = Book.new(
title: 'Rails E-Commerce 3nd Edition',
authors: [
Author.find_by(first_name: 'Christian', last_name: 'Hellsten'),
Author.find_by(first_name: 'Jarkko', last_name: 'Laine')
],
published_at: Time.now,
isbn: '123-123-123-x',
blurb: 'E-Commerce on Rails',
page_count: 300,
price: 30.5
)
apress.books << book
apress.reload
book.reload
assert_equal 3, apress.books.size
assert_equal 'Apress', book.publisher.name
end
Or instead of using fixtures, you could create the content before the test:
So that the test would look more like this:
setup do
publisher = Publisher.create!(name: 'Apress')
publisher.books.create!(title: 'Beginning Ruby')
publisher.books.create!(title: 'Ruby Recipes')
Author.create!(first_name: 'Christian', last_name: 'Hellsten')
Author.create!(first_name: 'Jarkko', last_name: 'Laine')
end
def test_has_many_and_belongs_to_mapping
apress = Publisher.find_by(name: 'Apress')
assert_equal 2, apress.books.size
book = Book.new(
title: 'Rails E-Commerce 3nd Edition',
authors: [
Author.find_by(first_name: 'Christian', last_name: 'Hellsten'),
Author.find_by(first_name: 'Jarkko', last_name: 'Laine')
],
published_at: Time.now,
isbn: '123-123-123-x',
blurb: 'E-Commerce on Rails',
page_count: 300,
price: 30.5
)
apress.books << book
apress.reload
book.reload
assert_equal 3, apress.books.size
assert_equal 'Apress', book.publisher.name
end
That way your database has those values, and your find_by() calls should return data, and not nil.

Rspec and Rails 4, update skip callback

I try to run an update test with rspec for my rails application.
I'm using rspec 3.5 and rails 4.
The behaviour is supposed to be the following :
When i create a new service with a selling price, it's create a Price instance and set the relation with the service. Then, when i update my service, if there is no selling price, it's destroy the price record (requirement of the client to save space in database).
The process i implemented seems to be working fine, when i test with the UI and i check the count of Price record, it's decrease by one like it's suppose. However, the unit test if failing.
Here is the code :
Service Controller :
def update
#service.assign_attributes(service_params)
puts "update method"
respond_to do |format|
if #service.valid?
if params['preview']
#service.build_previews
format.js { render 'services/preview' }
else
#service.save!
format.html { redirect_to client_trip_days_path(#client, #trip), notice: t('flash.services.update.notice') }
end
else
format.html { render :edit }
format.js { render :new }
end
end
end
The callback in the Service model :
def create_or_update_price
puts "in create or update price"
if selling_price.present? && price.present?
self.price.update_columns(:trip_id => trip.id, :currency => trip.client.currency, :purchase_price => purchase_price, :selling_price => selling_price)
elsif selling_price.present? && !price.present?
self.price = RegularPrice.create(:trip => trip, :currency => trip.client.currency, :purchase_price => purchase_price, :selling_price => selling_price)
elsif !selling_price.present? && price.present?
self.price.destroy
end
end
The test :
it "updates the lodging and destroy the price" do
puts "nombre de service avant création : "
puts Service.count
puts "nombre de prix avant création : "
puts Price.count
lodging = FactoryGirl.create(:lodging_service, selling_price: 200)
puts "nombre de service après création : "
puts Service.count
puts "nombre de prix après création : "
puts Price.count
expect(lodging.reload.price).to be_present
puts "nombre de prix avant update : "
puts Price.count
puts "id"
puts lodging.id
patch :update, client_id: client.id, trip_id: trip.id, id: lodging.to_param, service: valid_attributes_no_more_price
# patch :update, client_id: client.id, trip_id: trip.id, id: lodging.id, service: valid_attributes_with_price
puts "nombre de prix après update : "
puts Price.count
# expect{
# patch :update, client_id: client.id, trip_id: trip.id, id: lodging.id, service: valid_attributes_no_more_price
# }.to change(RegularPrice, :count).by(0)
expect(lodging.reload.price).to be_nil
end
let(:valid_attributes_no_more_price) {
attributes_for(:lodging_service, trip: trip, selling_price: "")
}
As you can see, there is a lot of puts since i try to find what is wrong.
The output is :
nombre de service avant création :
0
nombre de prix avant création :
0
in create or update price
nombre de service après création :
1
nombre de prix après création :
1
nombre de prix avant update :
1
id
10
nombre de prix après update :
1
Failure/Error: expect(lodging.reload.price).to be_nil
expected: nil
got: #<RegularPrice id: 2, label: nil, currency: "CHF", selling_price: 200.0, priceable_type: "Service", p...ated_at: "2017-07-13 08:08:47", quantity: 1, type: "RegularPrice", position: 1, purchase_price: nil>
As we can see, it's look like the callback is not fired after the update, and the action in the controller is not reached.
Have you any idea what is going wrong?
Thanks :)
PS: I always have trouble to include code in my questions, is there a tutorial on how to make it?
Since you did not mentioned your ruby version I'll assume it's 2.
First of all you need to learn how to properly debug your code in order to fix the issues yourself.
Here is what you have to do:
1.Add pry gem to your app, pry-byebug there is also a version for ruby 1.9.3.
2.Add a break point in your code
it "updates the lodging and destroy the price" do
(...) # Code here.
binding.pry # The debugger will open a console at this point
(...) # Maybe more code here
end
3.Verify all the variable and their values and see where the problem lies
In case you could not find the issue with binding.pry in your rspec file before the expect add it to after the first line of the method, and you can step through the debugger by typing next in the console opened by pry (it will be where your rails server is runnig).
If that still does not help, try and add a binding.pry in your classes and see what is the state in there.
Spend a few minutes/hours now to learn debugging and it will save you days/weeks in long term. (while you are learning you don't really know how a program should behave and that extra knowledge is priceless, after a while you only need a debugger for extremely complicated issues).

Record Persistence in Neo4j.rb 8.0.x

I am in the process of upgrading to Neo4j.rb version 8. After following the instructions in the upgrade guide, specs that were passing before are now failing.
Specifically, count, persisted?, all, last and find seem to have come unhinged from each other. I can create an account, see that is is persisted, see it if I count accounts, but not if I look for the last account, or all accounts, or try to find it from its id.
Output from console session below. Am I crazy?
[1] pry> account = Account.create(company_name: "Acme Corporation, LLC", street_address: "1234 Fake Lane", city: "Pleasantville", state: "CA", zip: "12345", country: "United States", phone: "555-555-5555", contact_name: "Some Guy", contact_phone: "123-456-7890", contact_email: "someguy#acmecorp.com")
=> #<Account uuid: "30c44118-ac45-4559-b63b-8e82fafb16cd", city: "Pleasantville", company_name: "Acme Corporation, LLC", contact_email: "someguy#acmecorp.com", contact_name: "Some Guy", contact_phone: "123-456-7890", country: "United States", created_at: Thu, 23 Mar 2017 19:13:52 +0000, phone: "555-555-5555", remote_id: nil, state: "CA", street_address: "1234 Fake Lane", updated_at: Thu, 23 Mar 2017 19:13:52 +0000, zip: "12345">
[2] pry> account.persisted?
=> true
[3] pry> Account.count
=> 1
[4] pry> Account.last
=> nil
[5] pry> Account.find(account.id)
Neo4j::ActiveNode::Labels::RecordNotFound: Couldn't find Account with 'uuid'=30c44118-ac45-4559-b63b-8e82fafb16cd
And the answer is....... RESTART YOUR COMPUTER AND EVERYTHING WORKS!!!111
In reality the problem was that somewhere along the line I deleted the database rather than stopping it, and then installed a new copy.

Activerecord::Relation: getting fields from a table

I'm trying to get an understanding about the inner features of Active Record playing with IRB.
I have a small database with a few tables which I created using SQL. Then I connected Active Record to that database using a Ruby script. I already loaded the models, which are classes with the tables' names singularized, and made all attributes accessible via attr_accessor but I only get the id and the rest return nil when trying to get them. Any clue?
I have the table "empresas" with four records and the class Empresa:
2.2.1 :001 > load 'config.db'
=> true
2.2.1 :002 > e = Empresa.all
=> #<ActiveRecord::Relation [#<Empresa id: 1, razon_social: "Holbrook Co.", cuit: "33-22564787-4", domicilio: "San Lorenzo 336", localidad_id: 7>, #<Empresa id: 2, razon_social: "Marshfield Llc.", cuit: "30-13547542-0", domicilio: "Av. de Mayo 110", localidad_id: 2>, #<Empresa id: 3, razon_social: "Iron Cobra Inc.", cuit: "30-24652120-8", domicilio: "9 de Julio 332", localidad_id: 20>, #<Empresa id: 4, razon_social: "Apple Inc.", cuit: "30-43753246-4", domicilio: "Riverside Road 342", localidad_id: 4>]>
2.2.1 :003 > e[2]
=> #<Empresa id: 3, razon_social: "Iron Cobra Inc.", cuit: "30-24652120-8", domicilio: "9 de Julio 332", localidad_id: 20>
2.2.1 :004 > e[2].id
=> 3
2.2.1 :005 > e[2].razon_social
=> nil
2.2.1 :006 > e[2].cuit
=> nil
The model looks like this:
class Empresa < ActiveRecord::Base
belongs_to :localidad
attr_accessor :razon_social, :cuit, :domicilio, :localidad_id
end
This model is required in the script that makes the connection to the database, along with active_record and fb (I'm using firebird for the database).
ActiveRecord will automatically create accessors for columns in your database tables.
When you define accessors with attr_accessor, you override those accessors.
Try removing that call to attr_accessor, then your calls should go on to the database values!

RSpec fixtures not loading

I am taking over a code base and am trying to run the tests. I am
somewhat new to RSpec so this might be a trivial problem.
Basically I can tell that the fixtures are not getting loaded. All 100
tests fail with a similar error.
But I don't know why. Below is the code. Where can I start looking?
In spec_helper.rb, which I know is running, I see:
Spec::Runner.configure do |config|
config.global_fixtures = :all
end
One of the tests in spec/controllers/downloads_controller_spec.rb
is below. I know it is running and I know that before the 'describe',
Partner.count == 0, so no fixture.
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe DownloadsController do
integrate_views
describe "when PDF is ready" do
before(:each) do
#registrant = Factory.create(:step_5_registrant)
stub(#registrant).merge_pdf { `touch #{#registrant.pdf_file_path}`
}
#registrant.generate_pdf
#registrant.save!
end
it "provides a link to download the PDF" do
get :show, :registrant_id => #registrant.to_param
assert_not_nil assigns[:registrant]
assert_response :success
assert_template "show"
assert_select "span.button a[target=_blank]"
assert_select "span.button a[onclick]"
end
after(:each) do
`rm #{#registrant.pdf_file_path}`
end
end
And here is what in various directories:
spec/fixtures/partners.yml - which contains 2 yaml records:
sponsor:
id: 1
username: rtv
email: rocky#example.com
crypted_password:
"c8e5b51b237344fe0e72539af0cac7197f094a5e933ffacf6e7fa612363c5933f520710c6427ac31fc4c68a2d7bb48eae601c74b96e7838f9ca1a0740b67576a"
password_salt: "Y4PPzYx2ert3vC0OhEMo"
name: Rocky
organization: Rock The Vote
url: http://rockthevote.com
address: 123 Wherever
city: Washington
state_id: 9
zip_code: 20001
phone: 555-555-1234
survey_question_1_en: "What school did you go to?"
survey_question_2_en: "What is your favorite musical group?"
created_at: <%= Time.now %>
updated_at: <%= Time.now %>
# TODO: remove partner 2 in production
partner:
id: 2
username: bull_winkle
email: bull_winkle#example.com
crypted_password:
"c8e5b51b237344fe0e72539af0cac7197f094a5e933ffacf6e7fa612363c5933f520710c6427ac31fc4c68a2d7bb48eae601c74b96e7838f9ca1a0740b67576a"
password_salt: "Y4PPzYx2ert3vC0OhEMo"
name: Bullwinkle
organization: Bullwinkle, Inc.
url: http://example.com
address: 123 Wherever
city: Washington
state_id: 9
zip_code: 20001
phone: 555-555-1234
survey_question_1_en: "What school did you go to?"
survey_question_2_en: "What is your favorite musical group?"
created_at: <%= Time.now %>
updated_at: <%= Time.now %>
Maybe this is done automatically now and you have solved it, but have you checked that your "spec/spec_helper.rb" contains:
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
Cheers

Resources