I am new to rails and trying to pass on some data in seeds.rb but doesn't show up when I do rails c
. I am trying to add reviews for an airline but the count shows up as 0 instead of 2. So it doesn't seem to be adding the reviews for the first airline somehow.
seeds.rb
airlines = Airline.create([{ name: "Air New Zealand", image_url: "url.com" },
{ name: "Jetstar", image_url: "https://www.jetstar.com/_/media/images/global/logos/jetstar-logo-black_svg.svg?la=en-NZ&hash=E2F625C27A6B66D3D129B3FB327F700503B14D7E" }])
reviews = Review.create([
{ title: "Good service", description: "service was good", score: 4, airline: airlines.first },
{ title: "Poor service", description: "service was poor", score: 2, airline: airlines.first },
])
schema.rb
ActiveRecord::Schema.define(version: 2021_04_17_115814) do
create_table "airlines", force: :cascade do |t|
t.string "name"
t.string "image_url"
t.string "slug"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "reviews", force: :cascade do |t|
t.string "title"
t.string "description"
t.integer "score"
t.integer "airline_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["airline_id"], name: "index_reviews_on_airline_id"
end
add_foreign_key "reviews", "airlines"
end
airline.rb
class Airline < ApplicationRecord
has_many :reviews
before_create :create_slug, :calculate_score
#create a slug like 'url.com/air-new-zealand' for an airline
def create_slug
self.slug = name.to_s.parameterize
end
def calculate_score
reviews.average(:score).to_f.round(2) * 100
end
end
review.rb
class Review < ApplicationRecord
belongs_to :airline
end
Aucun commentaire:
Enregistrer un commentaire