Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3, joining on more three tables

I would like to join more than three tables in Rails 3.

My code is

class offer < ActiveRecord::Base 

  belongs_to :user
  has_many :usercomments, :dependent => :destroy
  has_many :comments, :through => :usercomments, :dependent => :destroy

end

class User < ActiveRecord::Base

  has_many :usercomments, :dependent =>:destroy
  has_many :comments,:through => :usercomments, :dependent => :destroy
  has_many :offers, :dependent => :destroy

end 

class Usercomment < ActiveRecord::Base
  
  belongs_to :user
  belongs_to :comment
  belongs_to :offer

end

class Comment < ActiveRecord::Base
  
  has_one :usercomment, :dependent => :destroy
  has_one :offer, :through => :usercomments
  has_one :user, :through => :usercomments

end

My schema is:

create_table "offers", :force => true do |t|
  t.integer  "step_id"  
  t.integer  "user_id"  
  t.date     "offerdate"  
end

create_table "users", :force => true do |t|  
  t.string   "firstname",            :limit => 100, :default => ""  
  t.string   "lastname",             :limit => 100, :default => ""  
  t.string   "email",                :limit => 100  
end

create_table "usercomments", :force => true do |t|
  t.integer  "user_id"
  t.integer  "airoffer_id"
  t.integer  "comment_id"
  t.boolean  "shared"
end 

create_table "comments", :force => true do |t|
  t.string   "comment" 
  t.datetime "created_at"
  t.datetime "updated_at"
end

and index.html.erb is:

 <% airoffers.each do |airoffer| %>

???

 <% end %> 

In my html.erb page I would like to find a comment for an offer (offer_id) and an user (user_id).

like image 331
user488464 Avatar asked Oct 27 '10 10:10

user488464


1 Answers

It looks to me like what you want is:

class User < ActiveRecord::Base
   has_many :comments
   has_many :offers
end

class Offer < ActiveRecord::Base
   has_many :comments
   belongs_to :user
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :offer
end

If you want all the Comments that belong to a specific User and a specific Offer, just do Comment.where(:user_id => # :offer_id => #) and pass in the User and Offer you want.

Does this help?

like image 156
Adam Tanner Avatar answered Sep 28 '22 08:09

Adam Tanner