Consultation about relationship in Ruby on Rails

6

I'm starting in Rails and I could not find a relationship.

I have 3 tables: Video, donations and users. A user can put X videos and each video can have several donations.

  • On video I have the user_id
  • In Donations I have the user_id and video_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 take the user out of each video without problems:

video.user.name 

The problem is when I want to take the video title of a donation:

 <% @donaciones.each do |d| %>
      <%= d.video.titulo %><br>
 <% end %>

It always gives me:

undefined method 'titulo' for nil:NilClass

The title is in the videos table, I only have 1 record.

Is there any way to see the full query that is being made on the error page?

    
asked by Luisepvs 31.12.2015 в 08:28
source

1 answer

1

The code donacion.video.titulo what it does is look at the value of the attribute video_id of the donation and look in the table videos 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 that case donacion.video 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):

class Donation < ActiveRecord::Base
  belongs_to :video, required: true
end

You should also see how to avoid deleting videos and leaving orphan donations, for that you would have to use the :dependent option in the has_many, depending on how you want to solve the problem.

class Videos < ActiveRecord::Base
   has_many :donations, dependent: :restrict_with_exception
end

Finally, if you do not mind that there is no associated video, you can use a null object (of the "null-pattern") overwriting the video method:

class Donation < ActiveRecord::Base
  def video
    super || NullVideo
  end
end
    
answered by 01.01.2016 / 08:32
source