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?

2 Answers 2

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
1
  • 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, 2012 at 3: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
2
  • thx for answer, this makes sense but it's just not working :-( I'm using paperclip. Maybe try with no asset?
    – timpone
    Mar 24, 2012 at 4: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, 2012 at 6:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.