Невозможно получить значение атрибута из модели ActiveRecord - PullRequest
1 голос
/ 10 февраля 2012

Попытка получить значение из объекта не работает.

  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 ]

2 голосов
/ 10 февраля 2012

Быстрый ответ: 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 голосов
/ 10 февраля 2012

Кажется в _profiles.haml частичный рендеринг @ profile

Кажется, это работает

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

Не уверен, что он очень чистый, но пока что подойдет

...