Reputation: 872
Been stuck on this one for a while so I figured I'd throw it out there.
I have two models and a join model:
class Container < ActiveRecord::Base
has_many :theme_containers
has_many :themes, :through => :theme_containers
end
class Theme < ActiveRecord::Base
has_many :theme_containers
has_many :containers, :through => :theme_containers
end
class ThemeContainer < ActiveRecord::Base
belongs_to :container
belongs_to :theme
end
Grand. I know this association is working because in the console, when I type Theme.first.containers and Theme.first.theme_containers I get the models I expect (I've created the theme_container instances manually for the time being).
The issue is that in my form for theme I want to be able to update attributes on the join data, (theme_containers).
Here's a simplified version of my form:
<%= form_for(@theme) do |f| %>
<%= f.fields_for :theme_containers do |builder| %>
<%= render 'theme_container_fields', f: builder %>
<% end %>
<% end %>
When I run this, the container_fields partial is only rendered once and the builder object seems to be looking at the original @theme object. Is there something glaringly obviously wrong with my approach here? Is what I'm trying to do possible?
Also, I'm running rails 4 so I'm not using accepts_nested_attributes_for, and I have my strong parameters set up. I don't believe that should affect my specific issue but just throwing that out there too.
Thanks!
Upvotes: 3
Views: 682
Reputation: 41
What i would do is the following:
class Theme < ActiveRecord::Base
has_many :theme_containers
has_many :containers, :through => :theme_containers
accepts_nested_attributes_for :theme_containers
end
and in your ThemeController:
def new
@theme = Theme.new
Container.all.each do |container|
@theme.theme_container.build(container_id: container.id)
end
end
Upvotes: 1