3

バッジとバッジの勝者の 2 つのモデルを使用するフォームがあります。バッジにネストされている 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