Rails - Joinear tables of a model

0

Good morning, I have the following query that does not work for me:

  def self.search(profesor) ->pasa como parametro el nombre del profesor
    Curso.joins(:user).where("LOWER(users.name) LIKE ?", "%#{profesor}%")
  end

I have a course with a user_id attribute (corresponds to the teacher who gives that course)

I have the table user with an id and a name.

I need to ask a question where I bring all those courses where the teacher = user.name from the course model. Any ideas?

Thank you very much!

    
asked by hernan 08.09.2016 в 19:17
source

1 answer

1

I do not know how you have your models, but I think that in this case a relationship "one" to "many" is what you need.

I changed the name of the class from "Course" to "Courses" in English, just because rails pluralize the names (Course -> Courses).

Just something to take into account. The method is using the name of the teacher, as you require, however, you run the risk that there are two teachers with the same name and therefore show the courses of both teachers.

class Course < ActiveRecord::Base
  belongs_to :user

    def self.search(profesor)
      user = User.find_by(name: profesor) # encuentra al usuario
      Course.find_by(user_id: user.id) # encuentra los cursos de ese usuario
    end
end

class User < ActiveRecord::Base
  has_many :courses
end

I hope this helps you.

    
answered by 08.09.2016 в 23:32