Reputation: 12923
So I think I am missing something because of the following code bellow, I have included the error message, what I think is that tasks table doesn't have a task_id, but when I ran a migration to add task_id to tasks, it still gave me this error.
Routes
resources :tasks do
resources :comment
end
Model - comments
class Comment < ActiveRecord::Base
attr_accessible :author, :comment
belongs_to :tasks
has_one :author
validates :comment, :presence => true
end
Model Tasks
class Task < ActiveRecord::Base
attr_accessible :name, :task
has_many :comments, :dependent => :destroy
validates :name, :presence => true
end
Comments Controller
class CommentsController < ApplicationController
def index
@comment = Comment.new
@comments = Comment.all
end
def create
@task = Task.find(params[:id])
@comment = @task.Comment.create(params[:task])
redirect_to post_path(@task)
end
end
the form - partial
<%= form_for ([@task, @task.comments.build]) do |f| %>
<%= f.text_area :comment %>
<%= f.submit %>
<% end %>
Whats the issue?
unknown attribute: task_id
Extracted source (around line #1):
1: <%= form_for ([@task, @task.comments.build]) do |f| %>
2: <%= f.text_area :comment %>
3: <%= f.submit %>
4: <% end %>
Trace of template inclusion: app/views/tasks/show.html.erb
Rails.root: /home/adam/Documents/Aptana Studio 3 Workspace/StartPoint
Application Trace | Framework Trace | Full Trace
app/views/forms/_comments.html.erb:1:in `_app_views_forms__comments_html_erb___445541804__622889658'
app/views/tasks/show.html.erb:5:in `_app_views_tasks_show_html_erb___428009053_87363420'
Request
Parameters:
{"id"=>"3"}
Upvotes: 1
Views: 95
Reputation: 434675
what I am think is that tasks table doesn't have a task_id, but when I rad a migration to add task_id to tasks, it still gave me this error
You're thinking about the wrong table. When you say this:
class Comment < ActiveRecord::Base
belongs_to :task # Note that this should be singular as zeacuss notes below
end
ActiveRecord assumes that the comments
table will have a task_id
column to link back to the tasks
table. You don't need a migration to add tasks.task_id
, you need a migration to add comments.task_id
.
The ActiveRecord Associations Guide might make some good reading.
Upvotes: 2
Reputation: 2623
you should try
class Comment < ActiveRecord::Base
belongs_to :task
end
task
not tasks
as it is a one to one correspondence.
read more about belongs_to association here:
Upvotes: 1