0

我是铁轨新手,卡在奇怪的路口。问题与路线有关。下面是我的代码

路线$

resources :users do
 resources :requests 
end

用户.rb

class User < ActiveRecord::Base
 attr_accessor :password
 attr_accessible :email, :firstname, :lastname, :state, :city, :password
 has_many :requests ,:foreign_key => :user_id,:autosave => :true

请求.rb

class Request < ActiveRecord::Base
attr_accessible :email, :status, :user_id,:token
belongs_to :user

请求表单html

 <%= form_for (user_requests_path) do |f| %>
<div class="field">

<%= f.label "Email" %><br />
<div class="fieldgroup">

<%= f.text_field :email  , :class=>"textfield"%>

</div>
<div id="spacer">

</div>
<div class="fieldgroup">
<%= f.submit "Invite", :class=>"custombutton" %>
  </div>
   <% end %>
</div>

当我单击请求表单下的邀请按钮时,我遇到了以下错误,而不是调用 request#create。

路由错误

No route matches [POST] "/users/9/requests/new"

请求控制器

def create
@user = User.find(params[:user_id])
@request = @user.requests.create(params[:request])
redirect_to user_path(@user)
 end
4

3 回答 3

0

For nested resources, you need to pass both parameters to some helpers, so, e.g.,

user_request_path(@user, @request)

And so on. The Rails Resources Guide is a big help.

于 2013-02-08T19:52:35.730 回答
0

您需要传递用户对象,以便跟踪您引用的用户实例:

<%= form_for (user_requests_path(@user)) do |f| %>

也在:

has_many :requests ,:foreign_key => :user_id,:autosave => :true

不需要通过:foreign_key => :user_id,即默认外键,即“model_id”

于 2012-08-31T10:08:52.110 回答
0

为此,您应该routes.rb.

另请参阅:在 Rails 3 中路由嵌套资源

于 2012-08-29T09:09:15.587 回答