ruby-on-railsformsroutesurl-routingform-generator

Can I configure record identification to work with custom naming and a custom controller for a rails resource?


Suppose I have defined in my routes the following line

resources :a, controller: 'b', as: 'a'

and the following controller

class BController < ApplicationController
  ...
  def new
    @b = B.new
  end

  def edit
    @b = B.find(params[:id])
  end
end

Is there a way to write a form partial so that I can use it on both the new and edit views? For example, if I write

<%= form_for @b do |f| %>
  ...
<% end %>

Rails gives me a routing error.


Inelegant Solution

I came up with an inelegant solution to write the BController as

class BController < ApplicationController
  ...
  def new
    @b = B.new
    @url = bs_path
  end

  def edit
    @b = B.find(params[:id])
    @url = b_path
  end
end

and then write the form as

<%= form_for(@b, url: @url) do |f| %>
  ...
<% end %>

I wonder if there is a more "Rails" way to accomplish this though without having to write in the @url variable


Solution

  • Seems like you might be looking for the :path option to the resources...if I followed your example correctly, you have a model B and you want to access it at /a or /a/:id and be able to use a_path(instance_of_b)...so I feel like you want your route to be

    resources :b, as: 'a', path: 'a'
    

    and I believe that'll do what you're wanting.