model relation going both ways with foreign key - ruby-on-rails

I have two models reservations and reviews I can go reservation.review and get a correct output in cases. However, when i go review.reservation im not getting the same respect i get the relation error StatementInvalid.
Reviews model:
belongs_to :reservation, :foreign_key => :reservation_id, class_name: 'Reservation'
belongs_to :reviser
has_one :reviser
has_one :reservation
belongs_to :user
Reservation model:
has_one :review, :dependent => :destroy

A few things to note about your reviews model. You have this line:
belongs_to :reservation, :foreign_key => :reservation_id, class_name: 'Reservation'
but since you're naming the foreign key reservation_id, which is what rails names the foreign key by default, you can simply get rid of that part and say:
belongs_to :reservation
Secondly, I'm not totally sure why you have has_one :reservation since you already have belongs_to :reservation. I would probably delete the has_one :reservation line unless you're absolutely sure it should be there.
So your new reviews model would look like this:
belongs_to :reservation
belongs_to :reviser
has_one :reviser
belongs_to :user
I would double check in your schema.rb file to ensure that you have the field reservation_id in your reviews table. That field must be present for the association to work properly.

Related

Rails many to many relationship confusion

So im working on a rails app for users to create events (and attend other created events). You can read about the assignment here (for the Odin Project): https://www.theodinproject.com/courses/ruby-on-rails/lessons/associations
Anyways I thought I had understood many to many relationships in rails, but the way i've seen other people write the models is confusing to me.
To me it seems like it should be something like:
class User < ApplicationRecord
has_many :attendances
has_many :events, through: :attendances
end
class Attendance < ApplicationRecord
belongs_to :user
belongs_to :event
end
class Event < ApplicationRecord
has_many :users
has_many :users, through: :attendances
end
This makes sense to me because a User can create many events, and an event can have many users attending. (Although attendances is probably the wrong word, maybe invites or something).
But i've seen some weird examples (You can see others source code below on the project) and it seems like they are adding much more to the models and also renaming the source/foreign_key/class_name.
Am I missing something? This still allows a user to "own" an event right? Maybe im mis-understanding how many-to-many works. But this fits at least in my mind of how it should be.
For reference some other models I was seeing was similar to this:
class Event < ActiveRecord::Base
belongs_to :creator, :class_name => "User"
has_many :event_attendees, :foreign_key => :attended_event_id
has_many :attendees, :through => :event_attendees
end
class EventAttendee < ActiveRecord::Base
belongs_to :attendee, :class_name => "User"
belongs_to :attended_event, :class_name => "Event"
end
class User < ActiveRecord::Base
has_many :created_events, :foreign_key => :creator_id, :class_name => "Event"
has_many :event_attendees, :foreign_key => :attendee_id
has_many :attended_events, :through => :event_attendees, :foreign_key => :attendee_id'
end
Basically similar things to the above. Im not really sure what this is doing? Or why all the extra is necessary.
In your example everything according to conventions. Maybe except many-to-many table naming.
attendances table has 'user_id' and 'event_id' fields. But in case it could conflict with other fields, or not descriptive enough you could use different keys.
belongs_to :creator, :class_name => "User"
belongs_to :creator by default would look for Creator model, so it is needed to specify class name explicitly, like in the provided example.
has_many :event_attendees, :foreign_key => :attended_event_id
By default foreign key would be event_id, so here it is specified explicitly too.
has_many :created_events, :foreign_key => :creator_id, :class_name => "Event"
By default, rails would look for user_id foreign key and CreatedEvent model. And these attributes specified explicitly.
You just need to understand what attributes rails provides by default, to change if it is required.
ActiveRecord associations default to a class and foreign key with the same name as the association. The code here is specifically specifying these because they are not the default.

has_one through association with condition

I have 3 relevant tables/models. I would like to retrieve the user which has organized a party, given a Party record, a join table with a boolean organized column, and a users table.
My best attempt so far (this one makes the most sense to me after much fiddling). I've omitted the irrelevant columns.
class Party
# party_id
has_many :parties_users
has_many :users, through: :parties_users, source: :user
has_one :organizer,
-> { where organizer: true },
through: :parties_users,
source: :user
class PartiesUser
# party_id
# user_id
# organized:bool
belongs_to :party
belongs_to :user
class User
# user_id
has_many : parties_users
The above setup raises the following error, which I honestly don't fully understand:
ActiveRecord::HasOneThroughCantAssociateThroughCollection (Cannot have a has_one :through association 'Party#organizer' where the :through association 'Party#parties_users' is a collection. Specify a has_one or belongs_to association in the :through option instead.)
I know I can do this via an instance method, but given the frequency types of use, my app would massively benefit from having this as an association.
As the error message says, you can't have a has_one through a has_many.
You could (instead) do it this way if the organizer flag is on the join record...
has_many :parties_users
has_many :users, through: :parties_users, source: :user
has_one :main_party_user, -> {where organizer: true}, class_name: 'PartiesUser'
has_one :organizer, through: :main_party_user, class_name: 'User'

Rails 4.2 dependent: :destroy problems with CollectionProxy

I've used dependent: :destroy on models before with out any problem, but in rails 4.2 I'm stuck. The past uses were mainly for classic has_many belongs_to models. It almost seems that #<ActiveRecord::Associations::CollectionProxy is causing my problems.
Models
class Subject < ActiveRecord::Base
has_many :properties
has_many :values, :through => :properties
has_many :tags, :through => :properties
class Property < ActiveRecord::Base
belongs_to :subject
belongs_to :tag
belongs_to :value
class Value < ActiveRecord::Base
has_one :property
has_one :subject, :through => :property
has_one :tag, :through => :property
class Tag < ActiveRecord::Base
has_many :properties
has_many :subjects, :through => :properties
My goals were to
Deleting a Subject would delete all associated Properties and Values
Deleting a Property would delete the associated Value, leaving Subject intact
or, Deleting a Value would delete the associated Property, leaving Subject intact
I tried adding dependent destroy on the values line in Subject and the property line in Value. It would delete the properties, but not the values. I tried putting it on the values properties line and value line in Property and got the same results - it would not delete the Values.
I then tried before_destroy filter and ran into the same type of problem or a ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR when I tried the the model associations. I then hacked it and got it to work:
# In Subject model
before_destroy :destroy_values
def destroy_values
# relations does not seem to work got the Values using a new query
#values.destroy_all
pids = values.pluck(:id)
Value.where(id:pids).destroy_all
end
# in Value model
before_destroy :destroy_property
def destroy_property
property.destroy
end
Not sure what is going on, read up as much as I could on dependent and tried delete_all, and every other thing I saw with no joy!
Yes, it is a strange model, just playing around and tried to replicate the "Whatit?" Apple II database in rails for grins.
Sometimes, when your stuck going around circles, you just have to ask a question. When you don't get an answer, you've had time to rethink the problem. I guess I didn't try all the options.
I think the problem is my not understanding default strategy of nullify. According to my goals, you can't have a value without a property and vice versa. Trying to destroy using a through association would raise the pg error. The simple solution that I apparently didn't try was to dependent destroy properties in the Subject model and dependent destroy value in the Property model. The warning in the guide not to use dependent destroy on a belongs_to association may have started my circle trip. I'm still not sure I understand the warning. My guess is that when subject.properties is destroyed, the subject_id is set to null before the property.value destroy call is made, avoiding the pg error. My cleaned up models:
class Subject < ActiveRecord::Base
has_many :properties, dependent: :destroy
has_many :values, :through => :properties
has_many :tags, :through => :properties
class Property < ActiveRecord::Base
belongs_to :subject
belongs_to :tag
belongs_to :value, dependent: :destroy
class Value < ActiveRecord::Base
has_one :property
has_one :subject, :through => :property
has_one :tag, :through => :property

Mongoid::Errors::AmbiguousRelationship:

talk_groups table
field :parent_topic_id, type: Integer, default: -1
has_many :topics, :dependent => :destroy
belongs_to :parent_topic, :class_name => 'Topic', :foreign_key => :parent_topic_id
topics table
belongs_to :talk_group
The relation above works well on sqlite/mysql, but doesn't work on mongoid
because when a model can't have many and belongs_to with another same model
parent_topic.talk_group will appear Mongoid::Errors::AmbiguousRelationship: error
the problem is caused not because "when a model can't have many and belongs_to with another same model".
it's because when mongoid looks at the topic model, it can't know if the talk_group field is referring to the topics or parent_topic relation in the talk_group model.
mongoid provided an option to avoid this "AmbiguousRelationship" it's the inverse_of option...
so to solve this issue you should alter the topic model to become
belongs_to :talk_group, inverse_of: :parent_topic
and the talk_group model should become
has_many :topics, dependent: :destroy
belongs_to :parent_topic, class_name: 'Topic'
# you can add inverse_of option on this side as well although it's not mandatory
belongs_to :parent_topic, class_name: 'Topic', inverse_of: :talk_group
also refere to this question for more info.

Has_many through with multiple relationships between the entities

I have these model definitions:
class Property < ActiveRecord::Base
belongs_to :user
has_many :users_favourites_properties, class_name: 'UsersFavouritesProperties', dependent: :destroy, :foreign_key => :property_id
has_many :favourites, :class_name => "User", through: :users_favourites_properties
end
class User < ActiveRecord::Base
has_many :properties
has_many :users_favourites_properties, class_name: 'UsersFavouritesProperties', dependent: :destroy, :foreign_key => :user_id
has_many :favourites, class_name: "Property", through: :users_favourites_properties
end
class UsersFavouritesProperties < ActiveRecord::Base
self.table_name = "favourites"
belongs_to :favourites, class_name: 'User', :foreign_key => :user_id, :primary_key => :id
belongs_to :favourites, class_name: 'Property', :foreign_key => :property_id, :primary_key => :id, counter_cache: :users_count
end
When I execute:
current_user.favourites << property
The UsersFavouritesProperties object created has the same user_id and property_id because the user_id is beign setted with the property_id.
Do you know what is happening?
You seem to misunderstand what the association name is for.
Each association method call (like has_many) adds certain methods to a model that allow for easy lookup for associated objects.
The name of association means (in scope of a model) "what is it for me". A symbol you specify first is an association name, and it is used (among other things) as a name of a method that you will use to access that association.
By defining an association named favourites once, you've defined the methods for UsersFavouritesProperties. The second time you define an association with the same name, some of the first one is redefined and crazy things can happen.
So, following that "what is it for me" principle, you can figure that a User associated with a certain UsersFavouritesProperty is UsersFavouritesProperty's user, and the resulting association, that you have:
belongs_to :favourites, class_name: 'User', :foreign_key => :user_id, :primary_key => :id
should be more like simple:
belongs_to :user
The rest is not even needed, as it follows the Rails' convention: class name and foreign key can be derived from association name in standard ways (capitalize for class name, add _id for foreign key), primary key is default.
I strongly recommend you read the Rails Style Guide and let ActiveRecord guess the most you can provide.
These lines
belongs_to :favourites, ...
belongs_to :favourites, ...
Should be
belongs_to :user, ...
belongs_to :property, ...
You can't use two keys for belongs_to

Resources