2014年3月29日土曜日

Rails4時代のnested_attributes [error]undefined method `with_indifferent_access' for…

undefined method `with_indifferent_access' for…” when passing it nested attributes


というエラーが出て、うーんRails4になって久しぶりにいじるとなにがなんだかでしたが、解決したため記録しておきます。
mongoidを使ってますが、使い方はどっちも変わらないです。笑



class Article
  include Mongoid::Document
  include Mongoid::Timestamps
  field :title, type: String
  field :sub_title, type: String
  has_many :prices
  accepts_nested_attributes_for :prices #追加
end
class Price
  include Mongoid::Document
  field :article_id, type: String
  field :type, type: Integer
  belongs_to :article
end
class
ArticleController < ActionController::Base def create
@article = Article.new(article_params) #pricesを含めて入れてくれる
    @prices = @article.prices.build(article_params["prices"]) #不要
    @prices.save #不要
    respond_to do |format|
      if @article.save
        format.html { redirect_to @article, notice: 'Article was successfully created.' }
        format.json { render action: 'show', status: :created, location: @article }
      else
        format.html { render action: 'new' }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
end private
def article_params
    params.require(:article).permit(:title, :sub_title, prices_attributes: [:type]) #attribute名に注意
  end
end


<参考>
 Rails 4 permit nested attributes doesn't create/update || stackoverflow

“NoMethodError (undefined method `with_indifferent_access' for…” when passing it nested attributes || stackoverflow

Rails 4 Nested Attributes Unpermitted Parameters || stackoverflow

Strong Parameters || Rails公式サイト