Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1foreign-keysentity-relationship

Rails multiple model association


I have a rails application with the following Models:

User (id)
Version (id, post_id, creator_id)
Post (id)

So far setup is as follows:

User.rb:

has_many :versions

Version.rb:

belongs_to :creator, :class_name => "User"
belongs_to :post

Post.rb:

has_many :versions

Now i would like to link a user to the posts he has through the versions table, and to make it worst this connection must be called questions. I was thinking something like this:

Added to User.rb:

has_many :questions, :class_name => "Post", :source => :post, :through => :versions

Problem is this doesn't work and probably shouldn't since it doesn't know what the user key's name is in the versions table.

Error message:

SQLite3::SQLException: no such column: versions.user_id: SELECT COUNT(*) FROM "posts" INNER JOIN "versions" ON "posts"."id" = "versions"."post_id" WHERE "versions"."user_id" = 1

I'm at a loss, help!

Note: The only relationship that doesn't work is the final one users <==> posts a.k.a users.questions


Solution

  • This setup should work for you:

    user.rb

    has_many :versions, :foreign_key => 'creator_id'
    has_many :questions, :through => :versions
    

    version.rb

    belongs_to :creator, :class_name => "User"
    belongs_to :question, :class_name => "Post", :foreign_key => 'post_id'
    

    post.rb

    has_many :versions
    

    Now you can access the questions like so: User.first.questions