1

I have the following model structure

class Asset < ActiveRecord::Base
  attr_writer :session_user_id
  ...
end

class Item < ActiveRecord::Base
  has_many :assets, :as => :assetable, :dependent => :destroy
  ...
end

and want to put the user_id in the value associated with an asset. I am having a problem associating a variable on an uploaded file. Here's the post'd data:

"assets_attributes"=>{"3"=>{"asset"=>#<ActionDispatch::Http::UploadedFile:0x007fd04dde17f8 @original_filename="nautugly.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"menu_item[assets_attributes][3][asset]\"; filename=\"nautugly.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/var/folders/94/slp2488s6nvgg8qq0g0p5c0m0000gn/T/RackMultipart20120323-51480-1lpa754>>,
"description"=>""},...

and want to access a session_user_id in Asset. In the items_controller, I have added:

params[:item][:assets_attributes].each_with_index do |value, key|
  value.each do |y|
   y.asset.session_user_id=12
  end

but I get error msg:

undefined method `asset' for "3":String

I feel like I've tried every variation. How to get this to work?

Cœur
  • 37,241
  • 25
  • 195
  • 267
timpone
  • 19,235
  • 36
  • 121
  • 211

2 Answers2

0

I'm guessing here but how about using values instead of each_with_index.

params[:item][:assets_attributes].values do |y|
  y.asset.session_user_id=12
end
natedavisolds
  • 4,305
  • 1
  • 20
  • 25
  • hmm... this doesn't seem to be working. I am just trying to get the user_id asssociated with the asset. Shouldn't be this hard – timpone Mar 24 '12 at 03:50
0

So, there are a couple of things.

First, each_with_index called on a Hash will give you the object then the index. Since Hash defines each as an enumerable with two variables you will get key the value.

params[:item][:assets_attributes].each_with_index do |attr1, attr2|
  puts attr1 # ["3", {"asset" => "MyAsset!"}]
  puts attr2 # 0

  attr1.each do |value|
    puts value 
    # "3" on First Run
    # {"asset" => "MyAsset!"} on Second Run
  end
end

So if you just want to mess with the values then I suggest natedavisolds' approach. But that leads us to our second problem. Accessing a Hash; you need to do it using brackets[] not method calls.

All in all it should look something like this,

params[:item][:assets_attributes].values.each do |y|
  y[:session_user_id] = 12
end
Community
  • 1
  • 1
Azolo
  • 4,353
  • 1
  • 23
  • 31
  • thx for answer, this makes sense but it's just not working :-( I'm using paperclip. Maybe try with no asset? – timpone Mar 24 '12 at 04:49
  • I re-read your question, I thought `asset` was an embedded model. Now I realize it's actually an attribute of an `Asset`. So you would just strip [:asset] off the `Hash` index. – Azolo Mar 24 '12 at 06:11