I have a Boat Model and its Models such as Brand, Model and Year. I have also User model and I would like to connect them by adding migrations to User model of boat_id and I added belongs_to :boat and has_many :boats to User model. But I can not reach User.first.boat.name from the console even though I am able to reach Boat.first.brand.name.
When I try User.first.boat.name. Console gives an error saying;
NoMethodError: undefined method `boat' for #<User:0x0000000665dc30>
Btw: Boat Model includes model_id brand_id and year_id.
EDIT1:
Or should i remove Boat model and add model_id brand_id and year_id to User model directly.
EDIT2:
I would like to be able to reach User.first.boat.brand.name or User.first.boat.year.nameor User.first.boat.model.name
EDIT3:
Every boat has one brand, year and model. But user can have many boats
EDIT4:
What i will do is;
User can sign up and login
Then User press the link list my boat.
He/she saves the boat then the page renders to User Profile
In the User profile I do not know how to get current user boat name year etc. That is why I am confused. Sorry for the misunderstanding
I think you're confused about how Rails associations work in conjunction with how they are stored in the database. If a User can have many boats, then the foreign key needs to be on the boats table. Currently you have boat_id in the users table, this should be removed and a user_id column needs to be added to the boats table as per Matt's answer.
Reference
To achieve what you're trying to do, you'll need to setup your models in the following manner:
class User
has_many :boats
...
end
class Boat
belongs_to :user # table has a user_id column
...
end
Then you can access a boat's brand using user.boats.first.brand.name
Run rails generate migration, then fill in the change method as follows:
def change
add_column :boats, :user_id, :integer
end
Then run rake db:migrate.
You user model has_many boats, so you need the boats table to refer to users. It's probably worth reading the Rails guide for ActiveRecord associations to get a better feel for how this works: http://guides.rubyonrails.org/association_basics.html#the-has-many-association
Related
I have two models, one is called Employer and the other is called Student. Employers can view student profiles. How can I let employers save student profiles they like?
What I mean by that is, when the employer views a student profile and they like it, they must be able to click "save" and a link to that user profile will be saved and displayed on the employers profile. So when the employer goes to his own profile page, there will be a section called "Saved students" and links to the profiles of the students will be there.
I was thinking I add an array called "saved_profiles" to the employer model and then add a "save" button to the student profile. When an employer clicks it, the web address they are looking at right now, gets added to the saved_profiles array. By web address, I mean like "www.mywebsite.com/students/jake-madison". I'm not completely sure how to implement this though, any help on how to make this happen will be greatly appreciated.
An array on the "employers" table is what we would call a "denormalized" strategy. A "normalized" strategy would involve storing that save as a record in a join table. The denormalized solution is quick and easy - at first. It can cause headaches later on. So let's talk about the normalized solution using Rail's magical has many through association.
rails
class Employer
has_many :employer_students
has_many :students, through: :employer_students
class Student
class EmployerStudent
belongs_to :student
belongs_to :employer
database
table: students
columns: id, name
table: employers
columns: id, name
table: employer_students
columns: employer_id, student_id
When an employer "saves" a student's profile, we create a record in the employer_students table, linking that employer to that student. Then, when we want to see the students that an employer has saved, we do a join.
employer.students
i'm new to rails and your help and advise would be much appreciated as i am finding this challenging
Aim: i want the creator of the event to be able to select more than one user as
hosts for a created event (just like how facebook allows the creator of
a page to be be able to select users as admins of a created page). Is the below how my model and schema should be displayed?
i was aiming to build something like this image. Event1 i can select Ian & Jesse as hosts, Event2 i can also select Ian again as a host and select Emma
This is how i imagine it so far to be built (your guidance would be much appreciated):
models
user.rb
has_many events
event.rb
belongs_to user
host.rb
belongs_to user
has_many events
schema
users
name
email
events
title
address
user_id
hosts
user_id
event_id
Started writing this as a comment but realised it was getting too wordy.
your model is broken ... an event has many users .. it doesn't belong_to a single user.
What you have is a many to many relationship between users and events which needs resolving through a join table (aka associative/junction table). You have gone some way to resolving this with the hosts table though this goes against the rails convention.
What you want is something like:
models
user.rb
has_and_belongs_to_many :events
event.rb
has_and_belongs_to_many :users
and create a join table that references the two models
users table
name
email
events table
title
address
events_hosts table
user_id
event_id
The rails convention is for the join table to be named by joining the two names of the tables it is joining lexically ordered - i.e. events before hosts, concatenated together to give events_hosts.
Alternatively, you can also create a join model if you prefer:
EventHost
belongs_to :user
belongs_to :event
and modify the has_and_belongs_to_many to has_many :event_hosts in the other two models - the database schema will remain the same.
i have 3 model society and user now Society is manage by the admin model what happens is that when the user registers, the users "id" must be save simultaneously in the society models user_id field it has to happen with in the user_controller's create action
can somebody give me a simple code to do this
many thanks
To have your user_id assigned to the society, you should set up an association between User and Society. If has_one is the wrong association, please do some research on what type of association these need to be.
# app/models/user.rb
after_create :socialize
has_one :society
def socialize
self.society.create
end
References
Callbacks
Associations
So I have been trying to create a dummy application to try and learn Rails. The app I thought I could create is a coffee ordering app for a group of people in work.
So the website will have many users.
A user can create a coffee_order.
A coffee order contains orders for other individual users.
Each user can have one or more coffee_shop_items (e.g. latte,
cappuccino,danish, muffin, etc)
A coffee order also has an assignee, this is the person who is tasked
with going and getting the order.
So as a user, I create a coffee order, select an assignee, add users to the order, and add one or more coffee shop items to each user,
I am really struggling with how the database should be, and what the associations need to be, along with any join tables?
I am also trying to use nested attributes for the form entry.
Thanks in advance for help.
Update with some code I have tried to create a coffee order:
#coffee_order = CoffeeOrder.new(coffee_order_params)
params[:coffee_order][:user_coffee_orders_attributes].each do |user_order|
order = #coffee_order.user_coffee_orders.new(user_id: user_order[1][:user_id].to_i)
user_order[1][:coffee_shop_items].each do |item|
coffee_shop_item = CoffeeShopItems.find(item) if item != ""
# this line fails! see error below
#coffee_order.user_coffee_orders.coffee_shop_items << coffee_shop_item if coffee_shop_item != nil
end
end
error:
NoMethodError (undefined method `coffee_shop_items' for #<UserCoffeeOrder::ActiveRecord_Associations_CollectionProxy:0x42c6180>):
The coffee_shop_items belong to the order, not the user. After all, a user could probably create another order another day? You should probably also check out the rails documentation, which, IIRC actually contains a walk-through of a shopping cart application.
User has_many :coffes_orders
User has_many :coffee_orders_he_needs_to_get, class_name: "CoffeeOrder", foreign_key: "assignee_id"
CoffeeOrder belongs_to :user
CoffeeOrder belongs_to :assignee, class_name: "User"
CoffeeOrder has_and_belongs_to_many :coffee_shop_items
Coffee_shop_items has_and_belongs_to_many :coffee_orders
Just starting out with rails and I have a question. My grasp on associations is weak.
Lets say I have a model Cars
some cars will be rentals and some will not. So I created a table and a model called Rentals
which just has the car_id in it, designating that at car_id is a rental.
Right now I have a belong_to :cars line in my Rental model. And I'm not sure that's right. I am attempting to get a list of all the rentals easily. So grabbing the car_ids from the rental table and getting all the car information from the cars table the most efficient way.
Can someone help out?
The following:
Car.joins(:rentals).all # try with :rental if not working
Will output all the cars that have a rental object associated with ;)
It depends on what you will exactly need to do with it.
For simplicity, this is how I would do it.
class CarType #better than Rentals and more meaningful [:type => [rental, lease, own]]
belongs_to :car
end
class Car
has_one :car_type
end
So, now for the cars table, it will have a car_type_id pointing to the type in car_types table.