嵌套属性不在Rails表单中工作

时间:2012-03-10 00:30:06

标签: ruby-on-rails-3 forms rails-models

我有一个使用两种型号的表格 - 徽章和徽章获奖者。 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

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

0 个答案:

没有答案