无法从ActiveRecord模型获取属性值

时间:2012-02-10 09:00:29

标签: ruby-on-rails ruby-on-rails-3 activerecord carrierwave

尝试从对象获取值无法解决。

  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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

这似乎有效

  • @profile = User.find(profile.id).profile = image_tag @ profile.assets.first.file_url(:search)rescue nil

如果它非常干净但不是舒适但是现在它会做