0

I have a Task model:

## Task
has_many :children, :class_name => "Task"
belongs_to :parent, :class_name => "Task", :foreign_key => "parent_id"

Basically user has many tasks and each task has many child tasks.

I did this inside a view:

<%= render @tasks %>

And it used to work fine when the data structure was one dimensional.

However I keep getting the error message "(SQLite3::SQLException: no such column: tasks.task_id: SELECT "tasks".* FROM "tasks" WHERE "tasks"."task_id" = 138)" after adding the associations. I was expecting "parent_id", since that's what the model is supposed to refer to.

I am guessing that this is because of how rails implicitly connects the local variable "task" with its class "task". For example, I want to build a form inside comment like so:

## inside _task.html.erb
<%= form_for task.children.build do |f| %>
  <%= f.text_area :description %>
<% end %>

But it doesn't work because task.children gets an error saying that task doesn't have a column "task_id", when it's supposed to refer to "parent_id". Is there a way around this problem?

Vlad
  • 8,038
  • 14
  • 60
  • 92

2 Answers2

0

foreign_key

Specify the foreign key used for the association. By default this is guessed to be the name of the association with an “_id” suffix. So a class that defines a belongs_to :person association will use “person_id” as the default :foreign_key. Similarly, belongs_to :favorite_person, :class_name => "Person" will use a foreign key of “favorite_person_id”.

belongs_to :children, :class_name => "Task",:foreign_key => "parent_id"

You may want to use pk, Im not sure about the table structure.

Also, you may want to have a table many-to-many even if it is one way (one-to-many) for cleaner data. It will depend on the processes you need\use.

Community
  • 1
  • 1
Sully
  • 14,672
  • 5
  • 54
  • 79
  • I don't understand the answer. Are you saying I should model the association as parent and child pointing each other with belongs_to, and no has_many? As I wrote above, I already have :foreign_key => "parent_id" in my belongs_to :parent association. Also I don't understand why you're suggesting I model this as belongs_to :children instead of has_many :children. – Vlad Mar 23 '12 at 05:59
0

You need to rebuild your association.

has_many :children, :class_name => "Task", :foreign_key => "parent_id"
belongs_to :parent, :class_name => "Task"

Because below question proved that there is mistake in Rails documentation.

Ruby on Rails guides document on Activerecord association incorrect?

For your reference visit below question and see how the associations are used in this answer.

Rails Model has_many with multiple foreign_keys

Community
  • 1
  • 1
Soundar Rathinasamy
  • 6,658
  • 6
  • 29
  • 47