I have reviews ,users and airlines this is how to association is set up
class Airline < ApplicationRecord
has_many :reviews
has_many :users,through: :reviews
end
class Review < ApplicationRecord
belongs_to :user
belongs_to :airline
end
class User < ApplicationRecord
has_secure_password
has_many :reviews
has_many :airlines,through: :reviews
end
I want to do create method in my console... where I want to create a review by a particular user associated with a particular airline I know i can grab my user like this
u1=User.find_by_name("Max")
r1=u1.reviews.create("")
but how can I associate the airline I know there is something "where". I don't no how to write that command.
CodePudding user response:
It seems you just need to create the review:
u = User.find_by(name: 'Max')
a = Airline.find_by(name: 'Poop Airlines')
r = Review.create(review: 'This airline smells.', user: u, airline: a)
CodePudding user response:
I think you are on the right track. Since a review is created by a user for an airline, a review needs both user_id and airline_id.
In your code you have grabbed the user, now get the airline for which you want to create a record and then create a review
u1=User.find_by_name("Max")
a1 = Airline.find_by_name("Airline name")
r1=u1.reviews.create(review_column_name: "", airline: a1) //<replace review_column_name> to whatever your column name in db