mr_muscle
mr_muscle

Reputation: 2900

Rails can't create new object inside of ActiveAdmin controller

I'm working on messaging system between User and AdminUser. The User part is ready now I'm struggling how to allow Admin to send a reply to a conversation started by a User, inside of ActiveAdmin.

Code below:

# 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 %>

Which gives me an error:

First argument in form cannot contain nil or be empty Extracted source (around line #51): 51 <%= form_for [@conversation, @message] do |f| %>

When I tried to debug it turned out @message = nil inside of _show.html.erb. How is that possible if I defined @message inside of ActiveAdmin controller ?

[EDIT]

In case you're curious, ConversationController below:

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

Upvotes: 0

Views: 213

Answers (1)

matthew.tuck
matthew.tuck

Reputation: 1317

Normally you set up instance variables in your controller, and then Rails later does an implicit render of the view once the controller method completes.

However, it is possible to do an explicit render of the view, by calling something like render action: or render template: while the controller method is running, and presumably this is happening within the call to super.

See the Layout and Rendering Rails Guide for more information.

You'll need to move the assignment to be before the call to super.

You may also need to replace @conversation with resource in the ActiveAdmin controller (this is an ActiveAdmin/InheritedResources gem thing).

Upvotes: 1

Related Questions