Rails Association logic on event and ticket - database

I am writing an event application using ruby on rails and i am stuck on how to do the association effectively: the association is base on the following table User, Event, Ticket. The problem i have right now is the ticket and events, they are two type of tickets: free & paid which also have quantity.
i will be glad if anyone can help me with this association thanks.

Regarding the type of the ticket types you should look into STI.
Prerequisites:
# Gemfile
gem 'active_record_union'
It basically goes something like this:
class Ticket
end
class FreeTicket < Ticket
# Free-ticket stuff goes here
end
class PaidTicket < Ticket
validates :price, presence: true # and other paid-related checks
end
I suggest something along these lines for associations:
class Event # Also STI
end
class FreeEvent < Event
has_many :free_tickets
has_many :users, through: :free_tickets
end
class PaidEvent < Event
has_many :paid_tickets
has_many :users, through: :paid_tickets
end
class Ticket
belongs_to :event
belongs_to :user
scope :open, -> { where(user_id: nil) }
scope :taken, -> { where.not(user_id: nil) }
end
class User
has_many :free_tickets
has_many :paid_tickets
has_many :free_events, through :free_tickets
has_many :paid_events, through :paid_tickets
def events
free_events.union(paid_events)
end
end
This way you can do something like:
Event.find(1).tickets.count # => 13
Event.find(1).tickets.open.count # => 10
Event.find(1).tickets.taken.count # => 3
Event.find(1).users.count # => 3
User.find(1).events.count # => 1
User.find(1).free_events.count # => 0
User.find(1).paid_events.count # => 1

Related

Finding similar values in a hash/array in Ruby

I am trying to compute how many 'tips' a 'user' has in common with another user.
Here is my method doing so:
class User < ActiveRecord::Base
has_many :tips, :inverse_of => :user
...
public
def tip_affinity_with(user)
tipAffinity = 0
user.tips.each do |tip|
if self.tips.include?(tip)
tipAffinity = tipAffinity + 1
end
end
return tipAffinity
end
end
I know that some users have tips that they have both rated, but in my table, the tipAffinity is 0 for all of the users.
What could be the problem? Any help is greatly appreciated!
EDIT: Here is the join model, Affinity:
class Affinity < ActiveRecord::Base
attr_accessible :user_A_id, :user_B_id, :tips_value, :tips_valid, :profile_value, :profile_valid, :value
belongs_to :users
belongs_to :inverse_user, :class_name => "Users"
validates :tips_value, presence: true
validates :profile_value, presence: true
validates :user_A_id, presence: true
validates :user_B_id, presence: true
before_update :set_value
before_create :set_value
private
def set_value
self.value = 0.7*self.tips_value + 0.3*self.profile_value
#self.value = PredictionConfigs.find(1)*self.tips_value + (1 - PredictionConfigs.find(1))*self.profile_value #Use prediction configs
end
end
I am indeed trying to find the intersection of two hashes. The two hashes are the tips of two users, one is self, the other is user.
Thanks again!
Although this is brutally inefficient, you might try:
(user.tips & self.tips).length
You really want to avoid loading models if you're not using the data contained within them. This should be possible to compute using only what's present in the database. Something like:
(user.tip_ids & self.tip_ids).length
If your models are set up correctly, this can be done in the database with:
def tip_affinity_with(user)
user.tips.where(id: tip_ids).count
end
It seems to me based on the comments (and your example code) that your models may not be set up correctly. Do you have a join model between users and tips? Something like:
class User < ActiveRecord::Base
has_many :suggestions
has_many :tips, through: :suggestions
end
class Suggestion < ActiveRecord::Base
belongs_to :user
belongs_to :tip
end
class Tip < ActiveRecord::Base
has_many :suggestions
has_many :users, through: :suggestions
end
It'd help to see your Tip model. My guess is that Tip belongs_to :user and that's why you aren't getting any overlap between users, but I could be wrong.
Here's some more reading from the Rails guides on has_many :through associations.

Multiple Polymorphic Model in Rails

Hey So i have a basic schema that I am implementing. Here are the basic Models
User - Public Free User of App
Organization - Subscribes to app, has employees
Employee - Belongs to an organization
Here are my polymorphic parts
Post - Can be made by employees or users
Image - Multiple can be attached to either posts or comments
Comment - Can be added to images or posts by either employees or users
Users and Employees are distinct.
The polymorphic image is done. Where i am having trouble is the comment part. How do i set this up so that the comment can be associated with either images or posts and can be posted by either employees or users. Here is what i have so far.
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Post < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Image < ActiveRecord::Base
has_many :comments, :as => :commentable
end
This sets it up so that the comment can belong to the post or image, how do i set it up so that the employee/user can have many comments as they add them? Or should i just split this up into EmployeeComments and UserComments.
It seems like i will need another table that will host the polymorphic ownership association.
You should just need to add another polymorphic belongs_to association to the Comment model which will represent the author of the comment.
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
belongs_to :authorable, :polymorphic => true
end
class User < ActiveRecord::Base
has_many :comments, :as => :authorable
end
class Employee < ActiveRecord::Base
has_many :comments, :as => :authorable
end

Ruby on Rails 4: Polymorphic Association throws InverseOfAssociationNotFoundError

Two tables are having a has_one relationship to another table »Feedbacks« via polymorphic associations.
# Class Request
class Request < ActiveRecord::Base
belongs_to :user, inverse_of: :requests
has_one :feedback, as: :feedbackable
end
# Class Acceptance
class Acceptance < ActiveRecord::Base
belongs_to :user, inverse_of: :acceptances
has_one :feedback, as: :feedbackable
end
# Class Feedback
class Feedback < ActiveRecord::Base
belongs_to :feedbackable, polymorphic: true
belongs_to :user, inverse_of: :feedbacks
end
However, when trying to create a feedback associated to either requests or acceptances, the console throws me the error. Here's how I tried to create a feedback:
# First way
feedback = request.create_feedback(user_id: 2, message: "Hey, good driver!")
# Second way
feedback = Feedback.create(user_id: 1, message: "Hey, good driver!")
#user_id describes the user the feedback addresses
request = Request.create(user_id: 2)
#user_id describes the user the request comes from
request.feedback = feedback
This is the error that gets thrown:
ActiveRecord::InverseOfAssociationNotFoundError: Could not find the
inverse association for feedback (:request in Feedback)
Thanks in advance, I've been search everywhere and didn't find a similar problem :S
You might want to know what my database looks like:
class CreateAcceptances < ActiveRecord::Migration
def change
create_table :acceptances do |t|
t.references :user, index: true
t.timestamps
end
end
end
class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.references :user, index: true
t.timestamps
end
end
end
class CreateFeedbacks < ActiveRecord::Migration
def change
create_table :feedbacks do |t|
t.references :feedbackable, polymorphic: true
t.references :user, index: true
t.string :message
t.timestamps
end
end
end
Is the code you've posted exactly what is being run to generate that error message? Based on the error I would have expected the following Request code:
# Class Request
class Request < ActiveRecord::Base
belongs_to :user, inverse_of: :requests
has_one :feedback, as: :feedbackable, inverse_of: :request
end
Specifically that you were telling another activerecord to look inside Feedback for a :request association that it wasn't finding has_one :feedback, inverse_of: :request. This could be on any activerecord model, not necessarily request.rb. I ran into this exact same message in Rails 4.0.2 and removing the inverse_of: resolved the issue.

Mongoid unique model references

I'm using Mongoid 3. I have a simple class Tour and references multiple Itineraries. Is there a way that I can validate that for each tour, the itineraries' dates are unique, i.e. I can't have 2 itineraries of the same date for a single tour.
class Tour
has_many :itineraries
end
class Itinerary
field :date, :type => Date
validates :date, :presence => true
index({date: 1})
belongs_to :tour
end
I'm not sure how to set up the validation.
You can create custom validations :
class Tour
has_many :itineraries
validates :check_uniqueness_of_date # This line
# And this part
private
def check_uniqueness_of_date
# Check validation here
end
end
Another Stackoverflow Question
Rails Guides

Mongoid relational Polymorphic Association

Does anyone know how to do a polymorphic association in Mongoid that is of the relational favor but not the embedding one.
For instance this is my Assignment model:
class Assignment
include Mongoid::Document
include Mongoid::Timestamps
field :user
field :due_at, :type => Time
referenced_in :assignable, :inverse_of => :assignment
end
that can have a polymorphic relationship with multiple models:
class Project
include Mongoid::Document
include Mongoid::Timestamps
field :name, :type => String
references_many :assignments
end
This throws an error saying unknown constant Assignable. When I change the reference to embed, this all works as documented in Mongoid's documentation, but I need it to be reference.
Thanks!
Answering to an ancient post, but someone may find it useful.
Now there's also a polymorphic belongs_to:
class Action
include Mongoid::Document
include Mongoid::Timestamps::Created
field :action, type: Symbol
belongs_to :subject, :polymorphic => true
end
class User
include Mongoid::Document
include Mongoid::Timestamps
field :username, type: String
has_many :actions, :as => :subject
end
class Company
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
has_many :actions, :as => :subject
end
From Mongoid Google Group it looks like this is not supported. Here's the newest relevant post I found.
Anyway, this is not to hard to implement manually. Here's my polymorphic link called Subject.
Implementing inverse part of relation might be somewhat more complicated, especially because you will need same code across multiple classes.
class Notification
include Mongoid::Document
include Mongoid::Timestamps
field :type, :type => String
field :subject_type, :type => String
field :subject_id, :type => BSON::ObjectId
referenced_in :sender, :class_name => "User", :inverse_of => :sent_notifications
referenced_in :recipient, :class_name => "User", :inverse_of => :received_notifications
def subject
#subject ||= if subject_type && subject_id
subject_type.constantize.find(subject_id)
end
end
def subject=(subject)
self.subject_type = subject.class.name
self.subject_id = subject.id
end
end
Rails 4+
Here's how you would implement Polymorphic Associations in Mongoid for a Comment model that can belong to both a Post and Event model.
The Comment Model:
class Comment
include Mongoid::Document
belongs_to :commentable, polymorphic: true
# ...
end
Post / Event Models:
class Post
include Mongoid::Document
has_many :comments, as: :commentable
# ...
end
Using Concerns:
In Rails 4+, you can use the Concern pattern and create a new module called commentable in app/models/concerns:
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, as: :commentable
end
end
and just include this module in your models:
class Post
include Mongoid::Document
include Commentable
# ...
end

Resources