开发者

Create nested records on put/post with accepts_nested_attributes_for

开发者 https://www.devze.com 2023-03-22 05:16 出处:网络
I have two models, Landscape: class Landscape < ActiveRecord::Base has_many :images, :as => :imageable

I have two models,

Landscape:

class Landscape < ActiveRecord::Base
  has_many :images, :as => :imageable
  accepts_nested_attributes_for :images, :allow_destroy => true  
  attr_accessible :id, :name, :city, :state, :zip, :gps, :images, :images_attributes, :address1

  def autosave_associated_records_for_images 
    logger.info "in autosave"
    images.each do |image|
      if new_image = Image.find(image.id) then
        new_image.save!
      else
        self.images.build(image)
      end
    end
  end
end

Image:

class Image < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

I'm sending post and put requests from an iPhone to update/create a landscape record with json. Here's an example POST request to create a new landscape record and a new associated image record

{
  "landscape":{
    "id":0,
    "name":"New Landscape",
    "city":"The City",
    "state":"LA",
    "zip":"71457",
    "images_attributes":[
      {
        "id":0,
        "image_data":"image data image data image data",
        "is_thumbnail":1
      }
     ],
    "address1":"1800 Fancy Road"
  }

}

When the server receives this, it spits out

ActiveRecord::RecordNotFound (Couldn't find Image with ID=0 for Landscape with ID=0):

So this seems to be some kind of circular reference issue, but it's not clear how to go about fixing it. Also of interest is that the autosave_associated_records_for_images doesn't ever seem to be called (also there is almost no documentation for that function, I had to look at the rails source).

I've read just about every SO post on accepts_nested_attributes_for with no luck.

Update

I have the records creating now, but I can't get rails to pass the image data back to the Image model. Let me illustrate:

Started POST "/landscapes" for 127.0.0.1 at 2011-07-22 19:43:23 -0500
  Processing by LandscapesController#create as JSON
  Parameters: {"landscape"=>{"name"=>"asdf", "id"=>0, "address1"=>"asdf", "city"=>"asdf", "images_attributes"=>[{"id"=>0, "image_data"=>"Im开发者_StackOverflow社区 a bunch of image data image data image data", "is_thumbnail"=>1}]}}
  SQL (0.1ms)  BEGIN
  SQL (1.6ms)  describe `landscapes`
  AREL (0.2ms)  INSERT INTO `landscapes` (`address1`, `city`, `gps`, `name`, `state`, `zip`, `updated_at`, `created_at`) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, '2011-07-23 00:43:23', '2011-07-23 00:43:23')
  SQL (1.0ms)  describe `images`
  AREL (0.1ms)  INSERT INTO `images` (`image_caption`, `image_data`, `is_thumbnail`, `created_at`, `updated_at`, `imageable_id`, `imageable_type`) VALUES (NULL, NULL, NULL, '2011-07-23 00:43:23', '2011-07-23 00:43:23', 46, 'Landscape')
  SQL (0.2ms)  COMMIT
Completed 201 Created in 37ms (Views: 2.2ms | ActiveRecord: 14.5ms)

That's what happens when I don't define autosave_asociated_records_for_images. However, if I define it like so:

def autosave_associated_records_for_images
  logger.info "in autosave"
  logger.info images.to_s
end

I see the following output:

Started POST "/landscapes" for 127.0.0.1 at 2011-07-22 19:50:57 -0500
  Processing by LandscapesController#create as JSON
  Parameters: {"landscape"=>{"name"=>"asdf", "id"=>0, "address1"=>"asdf", "city"=>"asdf", "images_attributes"=>[{"id"=>0, "image_data"=>"Im a bunch of image data image data image data", "is_thumbnail"=>1}]}}
  SQL (0.1ms)  BEGIN
  SQL (1.6ms)  describe `landscapes`
  AREL (0.2ms)  INSERT INTO `landscapes` (`address1`, `city`, `gps`, `name`, `state`, `zip`, `updated_at`, `created_at`) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, '2011-07-23 00:50:57', '2011-07-23 00:50:57')
in autosave
[#<Image id: nil, image_caption: nil, image_data: nil, is_thumbnail: nil, created_at: nil, updated_at: nil, imageable_id: nil, imageable_type: "Landscape">]
  SQL (0.2ms)  COMMIT
Completed 201 Created in 32ms (Views: 2.2ms | ActiveRecord: 2.1ms)

This is very strange! It's creating the relationship properly, but it's not actually populating the database with the data I'm sending. Any ideas?


I never got either of the solutions here to work. What I did instead was do this manually in the controller by looping through the params.


I guess the error comes from:

Image.find(image.id)

Indeed this spits an exception when nothing is found.

Simply replace_it with:

Image.find_by_id(image.id)

It will spit nil if nothing found.


The autosave_associated_records_for_images method includes too much responsibilities for that Class. The solution is to move this method logic into Image class. Every ActiveRecord class instance have default callbacks, such as before_validation, before_create. I suggest you to use them first

0

精彩评论

暂无评论...
验证码 换一张
取 消