用于创建嵌套资源实例的表单
如何在父模型之外创建关联的模型实例?
我有一个嵌套资源
# 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
的帮助程序,它返回已登录的用户。此方法位于 ApplicationController
中包含的 SessionsHelper
模块中
# views/messages/new
= form_for current_user.messages.build do |f|
。视图中会输出错误
undefined method 'messages_path' for #<#<Class:0xHex_Number>:0xHex_Number
这个想法是允许用户在彼此之间发送消息。
How does one go about creating an associated model instance outside the parent model?
I have a nested resource
# 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
I followed the authentication procedures introduced in RailsTutorial.org; so I have a helper called current_user
that returns the user that is signed in. This method is in a SessionsHelper
module included in the ApplicationController
# views/messages/new
= form_for current_user.messages.build do |f|
This line in the view spits out an error
undefined method 'messages_path' for #<#<Class:0xHex_Number>:0xHex_Number
The idea is to allow users send messages amongst themselves.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通过在视图中构建占位符消息解决了视图层错误。
这使得可以呈现表单,但是当我提交表单时,浏览器向
new
操作发送了一个 POST 请求。控制台日志显示......这显然是错误的。根据 REST 理论,接收 get 请求的函数不应响应 POST 请求,即函数应该是特定于请求的。
为了解决这个问题,我更改了以下内容:
这样,在提交时,创建函数会收到 POST 请求。在控制台中...
...正如预期的那样。
I solved the view layer error by building a placeholder message in the view.
This enabled a form to be rendered but when I submitted the form, the browser sent a POST request to the
new
action. The console log read......which is obviously wrong. According to the REST theory, a function that receives a get request should not respond to a POST request i.e. functions should be request-specific.
To fix this, I changed the following:
This way, on submission, the create function receives a POST request. In the console...
...as expected.