I'm just starting out on Rails and haven't been able to find a relationship.
I have 3 tables: Video, donations and users. A user can put X videos and each video can have several donations.
- In video I have
user_id
- In Donations I have the
user_id
andvideo_id
My models are:
class Donation < ActiveRecord::Base
belongs_to :user
belongs_to :video
end
class Video < ActiveRecord::Base
belongs_to :user
has_many :donation
end
class User < ActiveRecord::Base
has_many :video
has_many :donation
end
I can get the user of each video without problems:
video.user.name
The problem occurs when I want to get the title of the video of a donation:
<% @donaciones.each do |d| %>
<%= d.video.titulo %><br>
<% end %>
always gives me:
undefined method `titulo' for nil:NilClass
The title is in the table videos
, I only have 1 record.
Is there a way to be able to see the full query being performed on the error page?
What the code
donacion.video.titulo
does is look at the valuevideo_id
of the donation attribute and search the videos table for the corresponding video.The problem is that in this case the video does not exist (because it was deleted for example) or the donation does not have an associated video, in this case
donacion.video
it is nil and you get that error.To avoid this, you can make the required relationship (to avoid having donations without videos in the database):
You should also see how to prevent videos from being deleted and leaving orphan donations, for that you would have to use the
:dependent
has_many option, depending on how you want to solve the problem.Lastly, if you don't mind that there is no associated video, you can use a null object (from the "null-pattern" pattern) by overriding the method
video
: