2012-03-31 45 views
0

所以我工作的地方有構成尋寶任務的項目。因此,當用戶點擊某個特定的狩獵時,我希望show.html.erb文件顯示狩獵以及與該狩獵相關的任務。我有通過HuntTask.rb連接的狩獵和任務模型。我創建了HuntTask模型,基於這裏的建議:Has and Belongs to Many error - *_development.hunts_tasks' doesn't exist:,但我仍然無法讓尋線控制器合理。由於錯誤的語法NameError在控制器連接表

def show 
    @hunt = Hunt.find(params[:id]) 
    @title = @hunt.name  
    @tasks = @hunt.tasks.paginate(:page => params[:page]) 
    end 

但隨後拋出了這個錯誤:

NameError in HuntsController#show 
    uninitialized constant Hunt::Hunttask 

這裏是我的模型是什麼樣子:

class Hunt < ActiveRecord::Base 
    has_many :hunttasks 
    has_many :tasks, :through => :hunttasks 
end 

class Task < ActiveRecord::Base 
    has_many :hunttasks 
    has_many :hunts, :through => :hunttasks 
end 

class HuntTask < ActiveRecord::Base 

    belongs_to :hunt, :class_name => "Hunt" 
    belongs_to :task, :class_name => "Task" 

我敢肯定的是,名稱錯誤是告訴我,滑軌不能找到一個名爲hunt表「,這是有道理的,因爲正確的表是‘狩獵’。但我不願改變我的表演方法的第三行,

@tasks = @hunt.tasks.paginate(:page => params[:page]) 

因爲我想指定@tasks方法應該將所有與顯示的特定搜索相關聯的所有任務,而不是全部搜索。我想我只是不明白我在@tasks中使用的語法。

當我將s添加到(@tasks = @hunts.tasks.paginate(:page => params[:page]))時,出現NilClass錯誤。

NoMethodError in HuntsController#show 
undefined method `tasks' for nil:NilClass 

但我不認爲任務應該是一種方法。或者是?

任何意見我應該做什麼?

回答

1

我想這應該是:

class Hunt < ActiveRecord::Base 
    has_many :hunt_tasks 
    has_many :tasks, :through => :hunt_tasks 
end 

class Task < ActiveRecord::Base 
    has_many :hunt_tasks 
    has_many :hunts, :through => :hunt_tasks 
end 

class HuntTask < ActiveRecord::Base 
    belongs_to :hunt # the id for the association is in this table 
    belongs_to :task 
end 
當你做這樣的事情 belongs_to :hunt, :class_name => "Hunt" 這似乎很直接,你並不需要做到萬無一失

,你應該問自己爲什麼。

+0

你說得對。我錯過了下劃線。引發錯誤的行是這一行:'@tasks = @ hunt.tasks.paginate(:page => params [:page])''。 – 2012-03-31 19:53:55

相關問題