Allan
Allan

Reputation: 343

Automaticly associate two models ruby on rails

I have 3 models:

Student - Class - Avaliation

I need that, when I associate a Student with a class, the student altomatcly is associated with one avaliation for that specific class.

A class has many students. The student belongs to many classes A student has many avaliation A Avaliation belongs to one student and one class.

When I open the url for the student, I need the avaliation to apear there so I can grade the student.

How can I do this?

Ok so this is my routes.rb

resources :students do
  resources :classrooms do
    resources :avaliations
  end
end

I can get students/1/classrooms/1/avaliation But in my students/show page i try this:

<p>
  <b>Name:</b>
  <%= @student.name %>
</p>

<h3>Class</h3>
<% @student.classrooms.each do |classroom| %>
    <%= classroom.name %>
<% end %>

But I get this Error:

SQLite3::SQLException: no such column: classrooms.graded: SELECT "classrooms".* FROM "classrooms" INNER JOIN "avaliations" ON "classrooms"."id" = "avaliations"."classroom_id" WHERE "avaliations"."student_id" = 1 AND ("classrooms"."graded" = 't')

Upvotes: 0

Views: 99

Answers (1)

Alex
Alex

Reputation: 2518

Untested:

class Avaliation
  belongs_to :student
  belongs_to :class
end

class Class
  has_many :avaliations
  has_many :students, :through => :avaliations, :conditions => {:graded => true}
end

class Student
  has_many :avaliations
  has_many :classes, :through => :avaliations, :conditions => {:graded => true}
end

Btw: Maybe you should find another name for your "Class"-Model. It could lead to some confusions ;)

Update: The above code assumes that you have at least the following columns in your database structure:

+-------------------------+
|Student (table students) |
|id: integer              |
|....                     |
+-------------------------+

+------------------------------+
|ClassRoom (table class_rooms) |
|id: integer                   |
|name:string                   |
|....                          |
+------------------------------+

+------------------------------+
|Avaliation (table avaliations)|
|student_id:integer            |
|class_room_id:integer         |
|graded:boolean                |
|...                           |
+------------------------------+

Upvotes: 0

Related Questions