how to have a unique calendar entity for each user entity? - ruby-on-rails

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'.

Related

How do I validate an unavailable period

I'm practicing rails and I would like to know how I would validate a situation.
In this case, it's a car rental project. I have a table of Cars (Autos) and one of Unavailable Period.
When registering a car, I assume that the car is available 100% of the month. If someone rents in a certain period, it must be unavailable so it can't be rented again in the same period, how would I do this validation?
Model
class UnavailablePeriod < ApplicationRecord
belongs_to :auto
end
class Auto < ApplicationRecord
belongs_to :rental_company
belongs_to :category
has_many :unavailable_periods
end
Any suggestion? content tip to study this?
What would be the best way?
model
Instead of an UnavailablePeriod I would simply have a Rental model that has a rented_from and a rented_until columns (both datetime).
On creation of a new Rental you then only have to check that there is no existing, date overlapping rental. to check that you could use a custom validation like this:
class Rental < ApplicationRecord
belongs_to :auto
validate :rental_period_is_available
private
def rental_period_is_available
return unless Rental
.where.not(id: id)
.where("rented_from < ? && ? < rented_until", rented_until, rented_from)
.exist?
errors.add(:base, "Car is already booked in this time period")
end
end
I suggest reading about custom validations and validations in general in the offical Rails Guides.

rails joining two tables together using has oen and has many

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 :)

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

Querying complex data in Rails 3.0

I have a data model where users have timelogs (which have dates).
I'm trying to query my DB in a way that will let me spit out a table of data, listing each user that has timelogs, and the sum of the time logged for each day in the period queried (similar in essence to a weekly timesheet).
I'm having problems figuring out a way of doing this. Any ideas?
A lot of the details will depend on your data model, but the short answer is to create a relationship first:
class User < ActiveRecord::Base
has_many :user_timelogs
has_many :timelogs, :through => :user_timelogs
end
class UserTimelog < ActiveRecord::Base
belongs_to :user
belongs_to :timelog
end
class Timelog < ActiveRecord::Base
has_many :user_timelogs
has_many :users, :through => :user_timelogs
end
Once you do that, you can query timelogs for users:
User.all.timelogs
You can add on additional queries (specific dates, sums, etc.). Check out the Rails guides for more info on how to narrow down that query:
http://guides.rubyonrails.org/active_record_querying.html
Try this, assuming the times are stored as number of seconds in a 'duration' column for each timelog row:
Timelog.where(...). # your time period
joins(:users).
group('users.id').
sum('duration')
This will give you a hash with the user ids as keys, and the sum of the durations as values.

User Presence In a chat room (chat getting updated by simple polling)

We have implemented a simple chat room feature in Rails using Simple Ajax updates. Now in every chat room a message belongs to particular user. We want to show the list of users(something like user presence). Please suggest ways. We are not using Jabber,XMPP etc.
The Chatroom model is:
class ChatRoom < ActiveRecord::Base
validates_presence_of :title
has_many :messages,:foreign_key=> "chat_room_id"
has_many :stories,:foreign_key=>"chat_room_id"
has_many :topics,:foreign_key=>"chat_room_id"
end
The messages are the chats sent of every user.
The message model is:
class Message < ActiveRecord::Base
belongs_to :user
end
The USer model is:
class User < ActiveRecord::Base
acts_as_authentic :crypto_provider => Authlogic::CryptoProviders::BCrypt
validates_presence_of :nick
validates_uniqueness_of :nick
has_many :questions
end
Please suggest ways
To keep track of which users are in which room, you could set up a HABTM relationship between the ChatRoom and User models. And, you could add a last_poll_datetime column to the User model to track the last time the user polled for messages (more on this part in a minute).
To show a list of all the users in a given room, use your HABTM join table, ChatRooms_Users. You'll be inserting/deleting from this table whenever a user joins or leaves a room.
If you want to expire users who close their browsers instead of clicking 'leave room', set up a sweeper task to run every minute that looks for users with last_poll_datetime older than one minute and remove their rows from the ChatRooms_Users join table.

Resources