Matthew Jeshua Martin
Matthew Jeshua Martin

Reputation: 11

Getting the ability to post in a model under a different controller Rails

I decided to make a clone of Facebook in Rails. First I'm working on getting status updates working. I got it setup as the StatusUpdate model that is called by the Pages controller to render on the index page.

The issue I'm having is that if I use form_for(@status_update) I get:

undefined method to_key' for
<StatusUpdate::ActiveRecord_Relation:0x00000000049d3448>
Did you mean? to_set to_ary

If I use form_with(model: @status_update):

undefined method to_model' for
<StatusUpdate::ActiveRecord_Relation:0x000000000471cd80>
Did you mean? to_xml

If I use form_with(model: status_update):

undefined local variable or method status_update' for
<#<Class:0x0000000005801678>:0x0000000002ec8ec8>
Did you mean? @status_update

My action:

def create
  @status_update = StatusUpdate.new(status_update_params)
  respond_to do |format|
    if @status_update.save
      format.html { redirect_to root_path, notice: 'Status successfully posted!' }
    else
      format.html { render :new }
    end
  end

and erb view:

<%= form_with(model: status_update) do |sp| %>
  <div class="form-group">
    <%= sp.label :status_update %>
    <%= sp.text_area :status_update, class: 'form-control', rows: 15, placeholder: 'Content' %>
  </div>
  <div class="form-group">
    <%= sp.submit 'Submit', class: 'btn btn-primary' %>
  </div>
<% end %>

Upvotes: 0

Views: 178

Answers (2)

max
max

Reputation: 101966

The argument to form_with must be a single model instance. Not a whole collection.

class Pages
  def index
    @status_updates = StatusUpdate.all
    @new_status_update = StatusUpdate.new
  end
end

---
# app/views/pages/index.html.erb
<%= form_with(model:  @new_status_update) %>
  # ...
<% end %>

<%= @status_updates.each do |s| %>
# ...
<% end %>

Which is why you need to pay attention to pluralization when naming variables!

Another way to solve this is by using a condition:

# app/views/status_updates/form.html.erb 
<%= form_with(model: local_assigns(:status_update) || StatusUpdate.new) %>
  ...
<% end %>

Which lets you use the form as a partial even without a StatusUpdate instance:

# app/views/pages/index.html.erb
<%= render partial: 'status_updates/form' %>

<%= @status_updates.each do |s| %>
  # ...
<% end %>

Upvotes: 0

Talha Junaid
Talha Junaid

Reputation: 944

I think you are missing the initialisation step. You have to first initialise the model object in new action of the controller.

def new
 @status_update = StatusUpdate.new
end

and then use it in form.

form_with(model: @status_update)

Upvotes: 1

Related Questions