在Rails中访问属性的奇怪问题

时间:2013-01-25 11:24:40

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

我可能是傻瓜,但是:

@activation_token = ActivationToken.where(:token => params[:id])
render(:text => @activation_token.inspect)

工作,并给出:

[#<ActivationToken id: 7, user_id: 21, token: "f4c3cb7c7629344e8261bf16e4a99900", used: false, created_at: "2013-01-25 10:48:57", updated_at: "2013-01-25 10:48:57">]

但是

@activation_token.user_id

抛出:

undefined method `user_id' for #<ActiveRecord::Relation:0x007fbfe414ff18>

我错过了什么?

1 个答案:

答案 0 :(得分:1)

尝试:

@activation_token.first.user_id

如果要访问@ activation_token.user_id,则提供对象集合,使用:

@activation_token = ActivationToken.where(:token => params[:id]).first
# or
@activation_token = ActivationToken.find_by_token(params[:id])