Trung
Trung

Reputation: 650

Ruby on Rails: ActiveRecord Associations

I'm new to Ruby on Rails.

I read some tutorial and knew how to create basic relationships. But I can't apply to my case.

I have 2 model look like

class User < ActiveRecord::Base
    attr_accessible :email, :created_user, :updated_user
    has_many :reports
end

and

class Report < ActiveRecord::Base
    attr_accessible :content, :user_id, :title, :updated_user 
    belongs_to :user
end

Now I can write:

report.user

But I want write somethings more

report.updated_user // instead of User.find(report[:updated_user]) 
user.created_user // instead of User.find(user[:created_user])
user.updated_user // instead of User.find(user[:updated_user])

What can I do?

Upvotes: 0

Views: 84

Answers (2)

visnu
visnu

Reputation: 935

try like this

@report=report.find(id)
@report.user.updated_user

Upvotes: 0

Jeroen
Jeroen

Reputation: 13257

Change your Report model to this:

class Report < ActiveRecord::Base
    attr_accessible :content, :user_id, :title, :updated_user 
    belongs_to :user, :class_name => "User", :foreign_key => 'user_id'
    belongs_to :updated_user, :class_name => "User", :foreign_key => 'updated_user'
end

Upvotes: 1

Related Questions