用于创建嵌套资源实例的表单

时间:2011-05-24 17:53:42

标签: ruby-on-rails associations

如何在父模型之外创建关联的模型实例?

我有一个嵌套资源

# config/routes.rb
resources :users do
    resources :messages
end

# models/user.rb
has_many :messages
# some other user model specifications

# models/messages.rb
belongs_to :user

我遵循了RailsTutorial.org中引入的身份验证过程;所以我有一个名为current_user的帮助器,它返回已登录的用户。此方法位于SessionsHelper

中包含的ApplicationController模块中
# views/messages/new
= form_for current_user.messages.build do |f|

视图中的这一行会显示错误

undefined method 'messages_path' for #<#<Class:0xHex_Number>:0xHex_Number

这个想法是允许用户在他们之间发送消息。

1 个答案:

答案 0 :(得分:0)

我通过在视图中构建占位符消息解决了视图层错误。

= form_for current_user.messages.build, :url new_user_message_path(:user_id => current_user do |f|

这使得表单能够呈现,但是当我提交表单时,浏览器向new操作发送了POST请求。控制台日志读取...

Started POST "/users/1/messages/new" for 127.0.0.1 at ...

ActionController::RoutingError (No route matches "/users/1/messages/new"):

......这显然是错误的。根据REST理论,接收get请求的函数不应响应POST请求,即函数应该是特定于请求的

要解决此问题,我更改了以下内容:

# controllers/messages
   def new
++   @message = Message.new
   end

# views/messages/new
-- form_for current_user.messages.build, :url new_user_message_path(:user_id => current_user do |f|
++ form_for [current_user, @message] do |f|

这样,在提交时,create函数会收到POST请求。在控制台......

Started POST "/users/1/messages" for 127.0.0.1 at ...
  Processing by MessagesController#create as HTML
  Parameters: {"authenticity_token"=>"areallylongstringthatnobodycanguess", "utf8"=>"✓", "message"=>{"title"=>"This is a breakthrough", "recipient"=>"Jamie", "content"=>"can you believe the developers got the messaging system working???"}, "user_id"=>"1"}
Completed   in 5ms

......正如所料。