无法从一个ActiveRecord模型得到属性值 [英] Unable to get attribute value from an ActiveRecord model

查看:118
本文介绍了无法从一个ActiveRecord模型得到属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图从一个对象中的值是不工作的。

 类资产<的ActiveRecord :: Base的
  attr_accessible:说明,
                  :文件,
                  :file_cache
  belongs_to的:可连接,
             多态=>真正
  mount_uploader:文件,AssetUploader
 

在控制台

 配置= Profile.first

  配置文件加载(0.5毫秒)选择`profiles`。* FROM`profiles`限制1等
 

profile.assets.inspect

 资产负载(0.6ms)选择`assets`。* FROM`assets` WHERE`assets`.`attachable_id` = 1和'assets`.`attachable_type` ='个人资料'
 => [#<资产ID:1,说明:无,文件:\fa731ee80a.jpg \,attachable_id:1,attachable_type:\档案\,created_at:\2012-01-30 0点29分21秒\的updated_at:\2012-02-07 22时13分十七秒\>]
 

我怎么会从这个文件的属性? 试了无数的事情,但我只是似乎无法弄明白

 配置= Profile.first然后profile.assets.first.file作品
 

 配置= Profile.where(:USER_ID => 2)然后profile.assets.first.file返回NoMethodError:未定义的方法`资产'的#<#
 

解决方案

快速回答: profile.assets.first.file

实际的回答:你的简介模型应该有一个 HAS_ONE:资产:为=> :可连接如果每个配置文件只能有一个附加的文件,但似乎你有一个的has_many

更新

尝试:

 配置= User.find(2)的.profile
profile.assets
 

或者

 配置= Profile.where(:USER_ID => 2)。首先
profile.assets
 

Trying to get a value from a object isn't working out.

  class Asset < ActiveRecord::Base
  attr_accessible :description,
                  :file,
                  :file_cache
  belongs_to :attachable,
             :polymorphic => true
  mount_uploader :file, AssetUploader

In console

  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\">]" 

How would I get the file attribute from this? Tried numerous things but I just seem to be unable to figure it out

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

BUT

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

解决方案

Quick answer: profile.assets.first.file

Actual answer: Your profile model should have a has_one :asset, :as => :attachable if each profile will only have one attached file, but it seems that you have a has_many.

Update

Try:

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

Or:

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

这篇关于无法从一个ActiveRecord模型得到属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆