如何解决Rails 无法在 ActiveAdmin 控制器内创建新对象
我正在研究 User
和 AdminUser
之间的消息传递系统。 User
部分现已准备就绪,我正在苦苦思索如何允许 Admin
对由 User
在 ActiveAdmin 内发起的对话发送回复。
代码如下:
# app/admin/conversations.rb
ActiveAdmin.register Conversation do
decorate_with ConversationDecorator
# ...
controller do
def show
super
@message = @conversation.messages.build
end
end
end
app/views/admin/conversations/_show.html.erb
# ...
<%= form_for [@conversation,@message] do |f| %>
<%= f.text_area :body %>
<%= f.text_field :messageable_id,value: current_user.id,type: "hidden" %>
<%= f.text_field :messageable_type,value: "#{current_user.class.name}",type: "hidden" %>
<%= f.submit "Send Reply" %>
<% end %>
<% end %>
这给了我一个错误:
表单中的第一个参数不能包含 nil 或为空 提取的源代码(围绕第 51 行): 51
当我尝试调试时,结果是 @message = nil
位于 _show.html.erb
内。如果我在 ActiveAdmin 控制器中定义了 @message,那怎么可能?
[编辑]
如果你好奇,下面的 ConversationController:
class ConversationsController < ApplicationController
before_action :authenticate_user!
def index
@admins = AdminUser.all
@conversations = Conversation.all
end
def new
@conversation = Conversation.new
@conversation.messages.build
end
def create
@conversation = Conversation.create!(conversation_params)
redirect_to conversation_messages_path(@conversation)
end
end
#routes
resources :conversations do
resources :messages
end
解决方法
通常您会在控制器中设置实例变量,然后 Rails 稍后会在控制器方法完成后对视图进行隐式渲染。
但是,通过在控制器方法运行时调用 render action:
或 render template:
之类的东西,可以对视图进行显式渲染,大概这是发生在对 super
的调用中。
有关详细信息,请参阅 Layout and Rendering Rails Guide。
您需要将分配移至调用 super
之前。
您可能还需要将 ActiveAdmin 控制器中的 @conversation
替换为 resource
(这是 ActiveAdmin/InheritedResources gem 的东西)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。