Osborne Saka
Osborne Saka

Reputation: 509

Form displays on the new routes and gives an error on edit route [Rails]

_form.html.erb

<%= form_with(model: [@seller, @seller_profile], local: true) do |form| %>
 
  <div class="field">
    <%= form.label :first_name %>
    <%= form.text_field :first_name %>
  </div>

  --- similar input structure ---

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>


This view works well on the new route, however, on the edit route is gives this error ActionView::Template::Error (undefined method `seller_profile_path' for #ActionView::Base:0x0000000001d060 Did you mean? seller_path):

Upvotes: 0

Views: 34

Answers (1)

max
max

Reputation: 101831

The error is most likely because @seller is nil. Rails calls #compact on the array so its thus equivalent to calling form_with(model: [@seller_profile]) which will look for the non-nested route helper.

You can solve it by setting @seller in the controller:

class SellerProfilesController < ApplicationController
  before_action :set_seller

  # ...

  private

  def set_seller 
    @seller = Seller.find(params[:seller_id])
  end
end

Or by using shallow nesting which avoids nesting the member routes (show, edit, update, destroy):

# config/routes.rb
resources :sellers do
  resource :seller_profiles, shallow: true
end
class SellerProfilesController < ApplicationController
  before_action :set_seller, only: [:new, :index, :create]

  # ...

  private

  def set_seller 
    @seller = Seller.find(params[:seller_id])
  end
end

Upvotes: 3

Related Questions