将站点从Rails 2.2.2迁移到Rails 3
我正在运行查询并将其存储在变量@user中但当我尝试访问@user的成员时,即使@user已经水合并且具有“is_admin”的值
,我也会收到错误### @user.inspect returns
[#<B2bUser id: 398, name: "Tim Test", email: "tim_test@test.com", username: "timtest", password: "foo", is_admin: true, company: "Test Co.", sent_welcome_email: true, created_at: "2011-12-14 08:32:31", send_email_reminders: false, api_username: "api.tim_test@test.com", api_password: "FOOBAR", login_attempts: nil, last_login_attempt_at: nil>]
但是当我从它的观点来看这个时:
<% if (@user.is_admin) %>
我明白了:
Completed 500 Internal Server Error in 15ms
ActionView::Template::Error (undefined method `is_admin' for #<ActiveRecord::Relation:0xaa5db4c>):
14:
15: <%= render :partial => "/warning" %>
16:
17: <% if (@user.is_admin) %>
18:
19:
20:
在同一视图中,当返回多于1行时会发生相同类型的错误(未定义的方法p.vendor_name),例如:
<% for p in @privileges %>
<% next if !p.can_setup_purchase_orders and !p.can_setup_instant_electronic_delivery %>
<h2>For <%= p.vendor_name %></h2>
这是我的控制器
class HomeController < ApplicationController
before_filter :authenticate
def index
@nav = []
@user = B2bUser.where(:id => request.session[:user_id])
#logger.debug @user.inspect
@privileges = B2bPrivilege.lookup_all request.session[:user_id]
#logger.debug @privileges.inspect
@can_asn = false
@can_push_xml = false
for p in @privileges
if p.can_setup_advance_ship_notification?
@can_asn = true and break
end
if p.can_setup_xml_pushes?
@can_push_xml = true and break
end
end
end
end
这是我的方法lookup_all class B2bPrivilege&lt;的ActiveRecord ::基
def B2bPrivilege.lookup_all current_user_id
#return B2bPrivilege.find(:all, :conditions => "b2b_user_id = #{current_user_id}", :joins => "LEFT JOIN vendors ON vendors.id = b2b_privileges.vendor_id", :select => "b2b_privileges.*, vendors.name AS vendor_name")
return B2bPrivilege.joins('LEFT JOIN vendors ON vendors.id = b2b_privileges.vendor_id').where('b2b_user_id' => current_user_id)
#return B2bPrivilege.find_by_sql["SELECT b2b_privileges.*, vendors.name AS vendor_name FROM b2b_privileges LEFT JOIN vendors ON vendors.id = b2b_privileges.vendor_id WHERE b2b_user_id = ?", current_user_id]
end
我是否需要以不同方式访问@user中的成员?这曾经在Rails 2.2.2 / Ruby 1.8.7中运行
由于
答案 0 :(得分:1)
如果你仔细观察,你会发现@user
实际上是一个ActiveRecord :: Relation对象,而不是User。如果您只有一个用户在该列表中,那么您可以使用@user.first.is_admin
到达所需的字段。
但是,将@user
设置为控制器中的第一个结果会更有意义。
UPDATE: 其中在rails中返回一个Relation,它是一个像object这样的数组。它不会返回单个模型记录。使用B2bUser.find(request.session[:user_id])
代替获取单个用户记录。