mardi 14 juillet 2015

Issues creating has_many through relation (Rails 4)

This may be a beginner question but it really has had me stumped tonight. I have 3 models: Play, User, and Works_on

app/models/play.rb

class Play < ActiveRecord::Base
  has_many :works_on
  has_many :users, through: :works_on, :foreign_key => 'user_id'
end

app/models/user.rb

class User < ActiveRecord::Base
  has_many :works_on
  has_many :plays, through: :works_on, :foreign_key => 'play_id'
end

app/model/works_on.rb

class WorksOn < ActiveRecord::Base
  belongs_to :user
  belongs_to :play
end

When I try to run

<%= @play.users.each{|user| user.first_name }  %>

in app/views/plays/show.html.erb, I get the error

SQLite3::SQLException: no such column: works_ons.play_id: SELECT "users".* FROM "users" INNER JOIN "works_ons" ON "users"."id" = "works_ons"."user_id" WHERE "works_ons"."play_id" = ?

I have tried creating a migration to manually add foreign keys to the models but have not been able to get it to work. Any help would be much appreciated.




Aucun commentaire:

Enregistrer un commentaire