2012-02-10 61 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如果每個個人資料將只有一個附加文件,但似乎你有一個has_many

更新

嘗試:

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

或者:

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

profile = Profile.first然後profile.assets.first.file工程BUT profile = Profile.where(:user_id => 2)then profile.assets.first.file返回一個NoMethodError:undefined方法'assets'爲#<#:0x007ff8eccd22f0>。 user_id 1和2都在db的assets列中有有效的資產,所以這個混淆了。 – Rubytastic 2012-02-10 09:13:58

+0

「user_id = 2」是否有多個配置文件? 'Profile.where(:user_id => 2).count> 1'? – bricker 2012-02-10 09:20:27

+0

bricker:不,返回false,db中的數據看起來很好,這就是爲什麼我無法掌握這個 – Rubytastic 2012-02-10 09:21:40

0

似乎在_profiles.haml部分呈現@profiles

這似乎是工作

  • @profile = User.find(profile.id)的.profile = IMAGE_TAG @ profile.assets.first.file_url(搜索)救援零

不舒爾如果很乾淨,雖然,但現在它會做