So perhaps I’ve found a bug in Rails 3.1.1, or else I don’t understand if Rails 3.1(.1) has changed in some way from Rails 3.0.10 with Nested Resources, Polymorphic associations, and/or routing…
Under Rails 3.0.10 the following works fine, but under Rails 3.1.1 it doesn’t!
These are my models:
class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
class Employee < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
My routes.rb:
resources :employees do
resources :pictures
end
resources :products do
resources :pictures
end
My controller:
class PicturesController < ApplicationController
def index
@imageable = find_imageable
@pictures = @imageable.pictures
end
private
def find_imageable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
My app/views/pictures/index.html.erb:
<% form_for [@imageable, Picture.new] do |f| %>
<p><%= f.submit "Add picture" %></p>
<% end %>
I generated the apps with rails new poly -T (for Rails 3.1.1 and for Rails 3.0.10).
I used standard scaffold commands: rails g scaffold Employee name:string, rails g scaffold Product title:string and rails g scaffold Picture caption:string imageable_id:integer imageable_type:string and then migrating, of course.
When hitting the index form (/employees first to create an employee with id == 1; then /employees/1/pictures) I get a blank form (no button appears) on Rails 3.1.1, and a form with the submit button on it, on Rails 3.0.10…
Any ideas if I’m doing something wrong in Rails 3.1.1, or have I really found a bug (I doubt it–I’m sure I’m doing something stupid!)?
In the line:
You are missing the
=after the<%. The line should beThe older style
<%syntax forform_for,field_foretc., was deprecated and scheduled for removal in 3.1, if I remember correctly.