0

Hi I have three tables like the following:

    class Workitem < ActiveRecord::Base
      has_many :effort
      attr_protected
    end

    class Effort < ActiveRecord::Base
      attr_protected
      belongs_to :workitem
      belongs_to :person
    end

    class Person < ActiveRecord::Base
      attr_accessible :given_name, :mgrid, :surname, :id
      has_many :effort
    end

The idea is to keep track of how many days a person has spent on a particular work item through efforts table. Could somebody verify if my relationships are correct? But this doesn't seem to work. Am I missing something here? Also, I can't understand the has_many :through kind of associations. Can somebody please give me an idea if that is what I'm supposed to use in this case?

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
anipendakur
  • 85
  • 10

1 Answers1

1

You would usually have the child as a plural object:

class Workitem < ActiveRecord::Base
  has_many :efforts
  attr_protected
end

class Person < ActiveRecord::Base
  attr_accessible :given_name, :mgrid, :surname, :id
  has_many :efforts
end

And I'd recommend using attr_accessible instead of attr_protected

If a Foo had many Bars and the Bars belonged to many Foos, it might look like this:

class Foo < ActiveRecord::Base
  has_many :foo_bar
  has_many :bars, through => :foo_bar
end

class Bar < ActiveRecord::Base
  has_many :foo_bar
  has_many :foos, through => :foo_bar
end

class FooBar
  belongs_to :foo
  belongs_to :bar
end

Something like that anyway. There's a load of help on Railcasts here

Also, there's a trillion examples on SO.

Hope that helps

simonmorley
  • 2,810
  • 4
  • 30
  • 61
  • 1
    Hi @simonmorley Thank you for the reply. I changed my child name to plural. However, I have another error that says effort.person_id does not exist. This is when I try the following from IRB: >p = Person.find 1234 >p.efforts ActiveRecord::StatementInvalid: PG::Error: ERROR: column efforts.person_id does not exist Am I going wrong somewhere again? :( – anipendakur Nov 21 '12 at 23:20
  • Have you created and run your migrations? And, you should use rails c not irb from within your project. – simonmorley Nov 21 '12 at 23:34
  • Hi, I have run my migrations. And I'm sorry, I meant to say rails console, not irb. My mistake. When I type in Effort.column_names in the console I get the column names, however it does not show any foreign keys (workitem_id, person_id). Do I need to add these columns to efforts table in another migration separately? – anipendakur Nov 21 '12 at 23:41
  • 1
    Yes, you'll need to create a migration and add these columns. Otherwise you'll not be able to look up the other. They're not virtual attributes. If you use a has_many_through rel. you won't need these, but you will need the additional join table – simonmorley Nov 21 '12 at 23:47