1

'Posts'コントローラーのcreate関数を介して送信するネストされたフォームがあります。1つの投稿には多くの場所があります。私の問題は、場所を「Find_Or_Create_by_name」まで設定したいのですが、投稿はしたくないということです。

私はこのようなものが解決策だと思います:

posts_controller.rb

def create
  @post = current_blogger.blog_posts.new(params[:post])    
  @post.locations = Location.find_or_create_by_name(params[:post])

  if @post.save
    redirect_to @post, notice: 'Blog post was successfully created.'
  else
    render action: "new"
  end
end

しかし、「each」エラーが発生します。

 undefined method `each' for #<Location:0x007fc5c1c2e5c8>

私はこれで正しい方向に進んでいますか?次のステップは何ですか?各「場所」を反復処理する必要がありますか?

どんな助けでも素晴らしいでしょう。

編集:これがログです:

Parameters: {"utf8"=>"✓",     authenticity_token"=>"Ffk65s3/aZqVcBvh9S/hOt7zYSighzyt6CSNDIuNt1Q=", "post"=>{"title"=>"This
  is about London", "body"=>"This is about London", "tag_list"=>"", "locations_attributes"=>
  {"0"=>{"_destroy"=>"false", "name"=>"London", "longitude"=>"-0.1276831", "la
  titude"=>"51.5073346"}}}, "_wysihtml5_mode"=>"1", "name"=>"London", "legname"=>"London",
 "longitude"=>"-0.1276831", "latitude"=>"51.5073346", "commit"=>"Submit"}
4

1 に答える 1

0

ロケーションモデルで

def self.find_or_initialize_location_set(location_set)
  locations = []
  location_set.each do |key, location|
    locations << find_or_initialize_by_name location
  end
  locations
end

次に、作成アクションで

def create
  location_set = params[:post].delete(:locations_attributes) unless params[:post][:locations_attributes].blank?
  @post = current_blogger.blog_posts.new(params[:post])
  @post.locations = Location.find_or_initialize_location_set(location_set) unless location_set.nil?
  if @post.save
    redirect_to @post, notice: 'Blog post was successfully created.'
  else
    render action: "new"
  end

終わり

于 2012-11-20T22:06:52.373 に答える