2012-02-10 59 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(搜索)救援零

不舒尔如果很干净,虽然,但现在它会做