2012-09-03 125 views
1

所以我想我錯過了一些東西,因爲下面的代碼如下,我已經包含了錯誤消息,我認爲這是任務表沒有task_id,但是當我運行遷移以添加task_id任務,它仍然給了我這個錯誤。未定義的屬性Task_ID

路線

resources :tasks do 
     resources :comment 
    end 

型號 - 評論

class Comment < ActiveRecord::Base 
    attr_accessible :author, :comment 
    belongs_to :tasks 
    has_one :author 
    validates :comment, :presence => true 
end 

型號任務

class Task < ActiveRecord::Base 
    attr_accessible :name, :task 
    has_many :comments, :dependent => :destroy 
    validates :name, :presence => true 
end 

條評論控制器

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 

形式 - 部分

<%= form_for ([@task, @task.comments.build]) do |f| %> 
    <%= f.text_area :comment %> 
    <%= f.submit %> 
<% end %> 

請告訴我這個問題?

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"} 

回答

2

什麼,我覺得是任務表沒有一個TASK_ID,但是當我RAD遷移添加到TASK_ID任務,它仍然給了我這個錯誤

你正在考慮錯誤的桌子。當你這樣說:

class Comment < ActiveRecord::Base 
    belongs_to :task # Note that this should be singular as zeacuss notes below 
end 

ActiveRecord的假設comments表將有task_id列鏈接回tasks表。您不需要遷移即可添加tasks.task_id,您需要遷移才能添加comments.task_id

ActiveRecord Associations Guide可能會使一些很好的閱讀。

1

你應該嘗試

class Comment < ActiveRecord::Base 
    belongs_to :task 
end 

tasktasks,因爲它是一一對應的。

閱讀更多關於belongs_to的關聯在這裏:

belongs_to