1

我有一个嵌套表单,它通过我的“帖子”控制器中的创建函数提交。一个帖子有很多位置。我的问题是我想将位置设置为“Find_Or_Create_by_name”,而不是帖子。

我认为这样的解决方案是:

post_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

但我得到一个“每个”错误。

 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 回答