2012-02-10 29 views
1

オブジェクトから値を取得しようとしていません。私はこのことから、ファイルの属性を取得する方法をActiveRecordモデルから属性値を取得できません

class Asset < ActiveRecord::Base 
    attr_accessible :description, 
        :file, 
        :file_cache 
    belongs_to :attachable, 
      :polymorphic => true 
    mount_uploader :file, AssetUploader 
コンソールで

profile = Profile.first 

    Profile Load (0.5ms) SELECT `profiles`.* FROM `profiles` LIMIT 1 etc 

profile.assets.inspect

Asset Load (0.6ms) SELECT `assets`.* FROM `assets` WHERE `assets`.`attachable_id` = 1 AND `assets`.`attachable_type` = 'Profile' 
=> "[#<Asset id: 1, description: nil, file: \"fa731ee80a.jpg\", attachable_id: 1, attachable_type: \"Profile\", created_at: \"2012-01-30 00:29:21\", updated_at: \"2012-02-07 22:13:17\">]" 

? は、多くの事をしようとしましたが、私はちょうどクイック答え

profile = Profile.first then profile.assets.first.file works 

しかし

profile = Profile.where(:user_id => 2) then profile.assets.first.file returns a NoMethodError: undefined method `assets' for #<# 

答えて

2

をそれを把握することができないように見える:profile.assets.first.file

実際の答え:あなたのprofileモデルがhas_one :asset, :as => :attachable各場合を持つべきですプロファイルに添付ファイルが1つしかありませんが、has_manyがあるようです。

更新

試してみてください。

profile = User.find(2).profile 
profile.assets 

または:_profiles.haml部分レンダリングが@profilesに

profile = Profile.where(:user_id => 2).first 
profile.assets 
+0

profile = profile.first then profile.assets.first.file works BUT profile = profile.where(:user_id => 2)then profile.assets.first.fileはNoMethodErrorを返します:未定義のメソッド 'assets ' #<#:0x007ff8eccd22f0>のために。 user_id 1と2の両方にdbのassets列に有効なアセットがあるため、この混乱が生じます。 – Rubytastic

+0

'user_id = 2'のプロファイルが複数ありますか? 'Profile.where(:user_id => 2).count> 1'? – bricker

+0

bricker:いいえ、falseを返します。dbのデータはうまくいきません。なぜ私はこれを把握できないのですか? – Rubytastic

0

ようだ

これが動作しているようです

  • @profile = User.find(profile.id)の.profile = IMAGE_TAG @ profile.assets.first.file_url(:検索)

nilの救助その非常にきれいな場合しかしSHUREが、今のところありませんそれは行うでしょう

関連する問題