2012-09-30 79 views
1

我希望用戶能夠創建一個挑戰(challenges_created),並且其他用戶能夠提供支持來實現它們(challenges_supported)。我試圖用一種自我加入的挑戰模型來做到這一點,其資源嵌套在用戶資源下面。我公司目前擁有車型:導軌自加入

class User < ActiveRecord::Base 
    attr_accessible :name, :supporter_id, :challenger_id 

    has_many :challenges_created, :class_name => 'Challenge', :foreign_key => :challenger_id 
    has_many :challenges_supported, :class_name => 'Challenge', :foreign_key => :supporter_id 
end 

class Challenge < ActiveRecord::Base 
    attr_accessible :challenger, :completion_date, :description, :duration, :status,  :supporter, :title 

    belongs_to :challenger, :class_name => 'User' 
    has_many :supporters, :class_name => 'User' 
end 

我認爲我會需要當用戶創建的挑戰,當他們支持他們既爲完整的CRUD和相應的視圖。因此,我創建了兩個名爲challenges_created_controller和challenges_supported_controller的控制器。

我的routes.rb文件是:

resources :users do 
    resources :challenges_created 
    resources :challenges_supported 
end 

,我與此設置遇到的問題是,當我嘗試

http://localhost:3000/users/3/challenges_created/new 

創建一個新的挑戰,我收到消息

Showing /home/james/Code/Rails/test_models/app/views/challenges_created/_form.html.erb where line #1 raised: 

undefined method `user_challenges_path' for #<# <Class:0x007fb154de09d8>:0x007fb1500c0f90> 
Extracted source (around line #1): 

1: <%= form_for [@user, @challenge] do |f| %> 
2: <% if @challenge.errors.any? %> 

結果對於編輯操作也是一樣的。我嘗試了很多東西,但是如果我在form_for中引用@challenge_created,那麼它與Challenge模型不匹配。

任何人都可以請建議我如何做錯了。先謝謝你。我的模式是:

create_table "users", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    t.integer "challenger_id" 
    t.integer "supporter_id" 
    end 

    create_table "challenges", :force => true do |t| 
    t.string "title" 
    t.text  "description" 
    t.integer "duration" 
    t.date  "completion_date" 
    t.string "status" 
    t.datetime "created_at",  :null => false 
    t.datetime "updated_at",  :null => false 
    t.integer "challenger_id" 
    t.integer "supporter_id" 
    end 

回答

0

我認爲問題是,你有一個challenge_created控制器,但你沒有模型它。在你的表單中,你指定了一個用戶和一個挑戰,以便導軌試圖找到一個挑戰的控制器,而不是challenge_created。 Rails認爲,對於一個模型,你有一個基於約定命名的控制器。

我建議你不要爲挑戰創建兩個不同的控制器。只對動作使用一種和差異。例如。您可以在挑戰中創建一個list_createdlist_supported行動。

+0

好的,謝謝你,這可以爲每一個平靜的控制器操作? – James

+0

我是否正確地指出,當遵循你的建議時,我不需要進一步修改上面提到的routes.rb? – James

+0

寧靜的行動可以分開,以適應兩個行動。這樣您可以在必要時重新定義默認路由。例如。你可以離開'new'動作,因爲用戶只能創建'challenge_created',刪除和修改也是一樣的,但是你需要單獨的列表。這些必須手動添加到路由。 – Matzi