rails joining two tables together using has oen and has many - ruby-on-rails

So I'm trying to link two models together
currently, I have tickets for events.
in the event model, I'm under the understanding that one event has one or more tickets so that would be a has many?
and in the tickets table, it would have one event?
In the tickets table, I have the event_id column.
Basically what I've wanting to have is the ability to type event.tickets.each for example to return all the tickets in the event

event.rb model
class Event < ActiveRecord::Base
has_many :tickets
end
ticket.rb model
class Ticket < ActiveRecord::Base
belongs_to :event
end
to fetch tickets of event do like below
event = Event.first
event.tickets.each do |ticket|
puts ticket.inspect
end

in ticket model add has_many :events
in event model add belongs_to :ticket
your events table should have a ticket_id foreign key.
this way you can do event.ticket
and also ticket.events
that is all :)

Related

Many to Many relation issue in Rails 4

I am a rails beginner and encountered the following issue
Models are setup as follows (many to many relation):
class Activity < ActiveRecord::Base
belongs_to :user
has_many :joinings
has_many :attendees, through: :joinings
end
class Joining < ActiveRecord::Base
belongs_to :activity
belongs_to :attendee
end
class Attendee < ActiveRecord::Base
has_many :joinings
has_many :activities, through: :joinings
end
This is one page test application for some users posting some activities, and other users to join the activities.
It is organized as single page format (activities index), and after each activity, there is a "Join" button users can click.
I am stuck at the point when a user needs to join a specific activity.
in the index.html.erb (of the activities), with the Join button code.
This will point to the attendee controller, to Create method, but I got no information regarding the Activity that I want to follow (eg. activity_id, or id)
Without this I cannot use the many to many relation to create the attendee.
What would be the correct button code, or any other suggestion to to get the corresponding activity ID in the attendees controller?
I tried a lot of alternatives, including even session[current_activity] , but is pointing (of course) always to the last activity.
Thanks so much !
If you have existing activities, and existing attendees, and you want to change the relationship between them, then you are editing the join table records. Therefore, you should have a controller for these. Like i said in my comment i'd strongly recomnmend renaming "joining" to "AttendeeActivity" so your schema looks like this:
class Activity < ActiveRecord::Base
belongs_to :user
has_many :attendee_activities
has_many :attendees, through: :attendee_activities
end
class AttendeeActivity < ActiveRecord::Base
belongs_to :activity
belongs_to :attendee
end
class Attendee < ActiveRecord::Base
has_many :attendee_activities
has_many :activities, through: :attendee_activities
end
Now, make an AttendeeActivitiesController, with the standard scaffoldy create/update/destroy methods.
Now, when you want to add an attendee to an activity, you're just creating an AttendeeActivity record. if you want to remove an attendee from an activity, you're destroying an AttendeeActivity record. Super simple.
EDIT
If you want to create an Attendee, and add them to an activity at the same time, then add a hidden field to the form triggered by the button:
<%= hidden_field_tag "attendee[activity_ids][]", activity.id %>
This will effectively call, when creating the attendee,
#attendee.activity_ids = [123]
thus adding them to activity 123 for example.
You have several options here. I'm assuming that the Join button will simply submit a hidden form to the attendees controller's create action. So the simplest solution would be to include the activity_id as a hidden form tag that gets submitted along with the rest of the form. This activity_id will be available in the params hash in the controller.
The other option is to setup Nested routing so that the activity_id is exposed via the path.
Thanks for all the details. I will change the naming of the join table for the future.
My problem was that I could not find the specific activity for attendee create method. Finally I found something like this for the JOIN button:
<%= button_to 'Join', attendees_path(:id => activity) %>
This will store the Activity ID, so I am able to find it in the Attendees controller:
def create
activity = Activity.find(params[:id])
#attendee = activity.attendees.create user_id: current_user.id
redirect_to activities_path
end
this updates also the Joinings (AttendeeActivity) table.
I will study about the hidden_field_tag solution, as is not clear to me yet.

Updating Tickets count from the Bookings model method

I'm creating a ticket booking app for my sample project using Ruby on Rails 4.1. Three are three models - Events, Tickets and Bookings. Events have many tickets and bookings. Tickets have many bookings and they belong to events. Bookings belongs to events and tickets.
Here's the ticket model:
class Ticket < ActiveRecord::Base
belongs_to :event
has_many :bookings
def maximum_tickets_allowed
(1..maximum_quantity.to_i).to_a
end
end
One of the model methods in Booking.rb is:
class Booking < ActiveRecord::Base
belongs_to :event
belongs_to :ticket
has_many :charges
def check_ticket_count
count = ticket.ticket_quantity.to_i - order_quantity.to_i
ticket.ticket_quantity = count
end
This method is used to print the number of remaining tickets after a successful and it works fine. I would like to know what's the best way to update the total tickets (ticket_quantity field in my table) with this value. I have seen some examples where they do it in controller. What's the Rails way?
I tried using ticket.ticket_quantity.save! and ticket.ticket_quantity.update etc. in the same model method but I encounter errors while doing it. Also, it would be great if you could point me to a resource that explores model methods in depth.
Currently you are not saving the ticket so the update is discarded.
Have you tried
count = ticket.ticket_quantity.to_i - order_quantity.to_i
ticket.update_attribute(:ticket_quantity,count)
update_attribute does not require a save as it auto saves without validations.
Although you should probably validate that the order_quantity is <= ticket_quantity
such as
class Booking < ActiveRecord::Base
...
#just threw this in for you too
after_create :update_ticket_count
validates :order_quantity, numericality:{less_than_or_equal_to: ->(booking){ booking.ticket.ticket_quantity}}
def update_ticket_count
ticket.update_attribute(:ticket_quantity,ticket.ticket_quantity.to_i - self.order_quantity)
end
end

ActiveRecord association between User and Event

I have a User and a Event model. I want to be able to associate each event with multiple attending users, and then have another user who is also among the attendees, be labeled as the owner, such that I would be able to make calls like #event.users, to retrieve all attendees, #event.owner, to retrieve the owner and then also be able to call #user.events, to get the events the user is attending.
Would it be most optimal to create a third model called Events_Users that keeps track of the relationship between users and events by storing a user_id together with an event_id, or just update the existing Event model with a user_id, along with the owner_id?
Please, some concrete suggestions will be much appreciated
Thanks
I would do it like this.
class Event < ActiveRecord::Base
belongs_to :owner, class_name: 'User'
has_and_belongs_to_many :attendees, class_name: 'User'
end
This way, you will have reference id to user in your events table (owner), and there will be join table for typical HABTM relationship for Users/Events (attendees for event).
Hope it helps!
Update
Here's associations for User class:
class User < ActiveRecord::Base
has_many :events
has_and_belongs_to_many :attended_events, class_name: 'Event'
end
Update 2
Here's the link to Rails Guide to Associations. It will explain how to create appropriate tables and columns for these kinds of relationships.

how to have a unique calendar entity for each user entity?

I am writing an application which will extensively use calendar for storing the daily information on various things, for each entity. Now how do I make a new calendar for each entity. Do I make a table for each entry in the user table?
Edit:
I am having an entity user.
Now for each entity there is a calendar for the whole year. for each day in the year there are 2 fields which will have some data.
now how do i make that? should i create a new table for each user? or should i just use foreign key of the user and have 365 entries in the calendar table for each user.
Edit:
Each user will only have one event each day.
also since the events occur on some item of the user, and the user has many items, so one user can have multiple calendars.
You will have one table for Users and one table for Calendar. This is what I would start with:
class User < ActiveRecord::Base
has_one :calendar
end
class Calendar < ActiveRecord::Base
belongs_to :user
has_many :calendar_events
end
class CalendarEvent < ActiveRecord::Base
belongs_to :calendar
end
Then you can do:
User.calendar.calendar_events #returns array of active record CalendarEvent objects
User.calendar.calendar_events.where(:start_date => Date.today) #assuming you have a start date field
These models will only be a bonafide calendar when you render the events in a grid that looks like a calendar.
EDIT
I think tester123 has a good answer to your question.
class User < ActiveRecord::Base
has_one :calendar
has_many :calendar_events, :through => :calendar
end
class Calendar < ActiveRecord::Base
belongs_to :user
has_many :calendar_events
end
class CalendarEvent < ActiveRecord::Base
belongs_to :calendar
end
In this case you have a table users and each user has its own calendar entry in table calendars. A user can also have 0 or more calendar_events. A calendar event has a column event_date (the day of the year you're talking about) and the two fields which have 'some data'.

How to create a Many-to-One relationship with existing records in Rails

I'm trying to implement something similar to that below. Basic setup is a Schedule model
class Schedule < ActiveRecord::Base
has_many :events
end
The Event model will then belong_to a Schedule.
Events are comprised of a name, datetime, running length and a Room
A Room is chosen from a select list when the event is created, all Rooms are created beforehand through seeding or admin interface. Room will store information like seating count.
I've been trying to find a method implementing this that feels right. Solutions seem to range between habtm or has_many :through but I can't see the need for a join table for this situation.
Theoretically, an Event has_one :room but the reverse relationship isn't belongs_to :event as a Room may be used for many events, this also requires the foreign key to be on the rooms table.
I've considered handling this manually in the model using a room_id foreign key in the event, I could then query for the relevant Room. I think this would work since I currently cannot see a requirement for finding all events using a Room.
class Event < ActiveRecord::Base
belongs_to :schedule
def room
Room.find(room_id)
end
end
Everything I've done so far in Rails has felt 'right', but all the solutions I've come up with here doesn't and I feel like I'm missing something; or maybe I'm just expecting that extra bit of magic.
Is there a "Rails" way to do this?
Wouldn't Event just have a belongs_to relationship to Room in this case?
class Event < ActiveRecord::Base
belongs_to :schedule
belongs_to :room
end
If you think about it from a schema perspective, your "events" table almost certainly has "schedule_id" and "room_id" columns.
The other side of the relationship is that a Room has_many Events.

Resources