3

我有一个使用两种模型的表格 - 徽章和徽章获得者。嵌套在徽章中的 badge_winners 需要 user_id 和 community_id 字段。我试图向 Ryan Bates 的 Railscast 学习(http://railscasts.com/episodes/196-nested-model-form-part-1

我得到的错误是:

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

第 42 行对应于 :create 中的这一行

@badge = Badge.new(params[:badge])

这是控制器:

def new
  @badge = Badge.new
  badge_winner = @badge.badge_winners.build
  respond_with(@badge)
end

def create
  @badge = Badge.new(params[:badge])
  if @badge.save
    flash[:notice] = "Badge was successfully created."
    redirect_to home_path
  else
    flash[:notice] = "There was a problem creating your badge."
    redirect_to home_path
  end     
end

这是表单(community_id 和 user_id 都填充得很好):

<%= 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 %>

模型(user_id 和 community_id 是 BadgeWinner 表中的字段):

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

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

这是一个类似的问题,但我没有语法原因: Form with nested attributes with a has_one association not working in Rails 3

我希望有人能够提供帮助。我只知道这是某个地方的新手错误。提前感谢您的任何帮助!

4

0 回答 0