我希望用户能够创建挑战 (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 和相应的视图,无论是用户创造挑战还是支持挑战。因此,我创建了 2 个控制器,分别命名为 challenge_created_controller 和 challenge_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