【问题标题】:Rails can't create new object inside of ActiveAdmin controllerRails 无法在 ActiveAdmin 控制器内创建新对象
【发布时间】:2021-06-03 11:18:14
【问题描述】:

我正在处理UserAdminUser 之间的消息传递系统。 User 部分现在已准备就绪我正在努力如何允许Admin 发送对由 ActiveAdmin 内部的User 发起的对话的回复。

代码如下:

# 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

【问题讨论】:

    标签: ruby-on-rails activeadmin


    【解决方案1】:

    通常您在控制器中设置实例变量,然后 Rails 稍后会在控制器方法完成后对视图进行隐式渲染。

    但是,可以通过在控制器方法运行时调用 render action:render template: 之类的东西来对视图进行显式渲染,这可能是在调用中发生的到super

    请参阅Layout and Rendering Rails Guide 了解更多信息。

    您需要将分配移动到调用 super 之前。

    您可能还需要在 ActiveAdmin 控制器中将 @conversation 替换为 resource(这是 ActiveAdmin/InheritedResources gem 的东西)。

    【讨论】:

    • 有一点你是对的——分配应该在super之前。但即使我这样做了,我仍然有@message = nil 错误。 Monkey 解决方案是将对话声明为def show; @current_conversation = Conversation.find(params[:id]); @message = @current_conversation.messages.build; super,它可以工作。但我认为我不应该这样做
    • @mr_muscle 这与您之前的@​​987654332@ 分配完全相同,只是使用了不同的变量。我非常怀疑一个给 nil 而另一个工作 - build 不会返回 nil。我可以相信有人给出了 NilClass UndefinedMethodError,因为 @conversation 是 nil,但我已经在我的帖子中使用了 resource
    • 同时重启你的服务器,因为根据我的经验,AA 并不总是正确地重新加载代码。
    • 没错,问题出在@conversation 内部,因此我明确声明——我的错误。如果我用resource 替换@conversation 它不会改变任何东西,仍然是同样的错误。服务器重启,spring stop也不行。
    • @mr_muscle 这两件事应该是等价的。 resource 方法的源代码在这里:github.com/activeadmin/inherited_resources/blob/… 除非你之前设置了@conversation 或覆盖了关联链,否则都是一样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多