Nested Attributes Not Working in Rails Form

I have a form that uses two models - winners and badges. The user_id and community_id fields are required for badge_winners, which is nested in badges. I tried to learn from Rails Bates Railscast ( )

The error I am getting:

ActiveRecord::UnknownAttributeError in BadgesController#create
unknown attribute: user_id
app/controllers/badges_controller.rb:42:in `new'


Line 42 matches this line in: create

@badge =[:badge])


here's the controller:

def new
  @badge =
  badge_winner =

def create
  @badge =[:badge])
    flash[:notice] = "Badge was successfully created."
    redirect_to home_path
    flash[:notice] = "There was a problem creating your badge."
    redirect_to home_path


Here's the form (both community_id and user_id fill out fine):

<%= form_for(@badge) do |f| %>

  <%= f.label :Description %>
  <%= f.text_area :description %>

  <%= f.fields_for :badge_winners do |builder| %>
     <%= builder.hidden_field :user_id ,:value => user_id %>
     <%= builder.hidden_field :community_id ,:value => community_id %>
  <% end %>

  <%= f.submit "Give Badge" %>
<% end %>


Models (user_id and community_id are fields in the BadgeWinner table):

class Badge < ActiveRecord::Base
  belongs_to :community
  has_many :badge_winners, :dependent=>:destroy
  accepts_nested_attributes_for :badge_winners

class BadgeWinner < ActiveRecord::Base
  belongs_to :user
  belongs_to :badge


This is a similar problem, but I have no syntax reason: Form with nested attributes with has_one association not working in Rails 3

I hope someone can help. I just know this is a beginner's mistake. Thanks in advance for your help!


source to share

All Articles