Search code examples
ruby-on-railsrubyruby-on-rails-3routessingle-table-inheritance

Handling forms with Single Table Inheritance


I have a form in my Profile edit view beginning with this line:

<% form_for @profile, :html => { :multipart => true } do |f| %>

Profile undergoes Single Table Inheritance and the two subclasses are Profile::Artist and Profile::Listener.

When I try to access the edit view for the profile, I get this error:

NoMethodError in Profiles#edit

Showing /rubyprograms/dreamstill/app/views/profiles/edit.html.erb where line #1 raised:

undefined method `profile_artist_path' for #<#<Class:0x103359a18>:0x1033560c0>

where lines 1 is the line of code for the form that I posted above. How can I fix this error?

UPDATE:

I added this code to my Profile model:

def self.inherited(child)
  child.instance_eval do
    def model_name
      Vehicle.model_name
    end
  end
  super
end

And now my error has changed to:

NameError in Profiles#edit

Showing /rubyprograms/dreamstill/app/views/profiles/edit.html.erb where line #1 raised:

uninitialized constant Profile::Vehicle

UPDATE 2:

I changed the first line of the form to:

<% form_for(:profile, @profile, :url => {:controller => "profiles", :action => "update"}, :html => { :multipart => true }) do |f| %>

and the submit button to <%= f.submit :profile %>

Now I just get a routes error...


Solution

  • Not Vehile but Profile!

    def self.inherited(child)
      child.instance_eval do
        def model_name
          Profile.model_name
        end
      end
      super
    end
    

    or

    def self.model_name
      name = "profile"
      name.instance_eval do
        def plural;   pluralize;   end
        def singular; singularize; end
        def i18n_key; singularize; end
        def human(*args); singularize; end
      end
      return name
    end
    

    UPDATE

    An actual problem was in form. You should add :method => :put

    <%= form_for(@profile, :html => { :multipart => true, :method => :put }) do |f| %>