在Rails中显示数据时出错

问题描述 投票:1回答:3

我正在尝试在视图中显示成员的个人资料。当我在变量上运行inspect选项时,它会打印出profile变量上的所有数据。但是,当我只调用一列时,我收到一个错误。

我在不同的变量上运行相同的代码并打印出来;所以,我对发生的事情感到有点困惑。是因为Active Record有关系吗?这是代码:

profiles_controller.rb

def show
  @show_page = params[:id]
  @member = current_member
  @profile = Profile.where(member_id: current_member.id)    
end

show.html.erb

<hr>
<%= @show_page.inspect %>
<hr>
<%= @profile.inspect %>
<hr>
<%= @member.inspect %>
<hr>

<p>
  <strong>Member ID:</strong>
  <%= @member.id %>
</p>

在浏览器中查看

"8"

#<ActiveRecord::Relation [#<Profile id: 6, f_name: "Test", l_name: "Member", u_name: "testing", security: "10", private: "1", avatar: nil, birthday: nil, phone: nil, address1: nil, address2: nil, city: nil, state: nil, zip: nil, long: nil, lat: nil, facebook: nil, twitter: nil, instagram: nil, pinterest: nil, googleplus: nil, motto: nil, created_at: "2017-12-23 05:15:53", updated_at: "2017-12-23 05:15:53", member_id: 8>]>

#<Member id: 8, email: "[email protected]", created_at: "2017-12-19 20:02:34", updated_at: "2017-12-23 05:15:37">

Member ID: 8

现在,当我将以下代码添加到显示页面时,我收到一个错误。

show.html.erb

<p>
  <strong>User Name:</strong>
  <%= @profile.u_name %>
</p>

错误

Showing /Users/topher/Dropbox/railsapps/~sandboxes/temporary/app/views/profiles/show.html.erb where line #21 raised:

undefined method `u_name' for #<Profile::ActiveRecord_Relation:0x00007fcb2583b920>
Did you mean?  name

如果有一种不同的方式需要调用变量中的数据,我只是感到困惑。我能看到的@member@profile打印输出的唯一区别是#<ActiveRecord::Relation [前缀为@profile。这是否意味着我需要以不同方式调用信息?

ruby-on-rails database
3个回答
1
投票

#where是查询方法,返回与ActiveRecord::Relation对象中包含的查询条件匹配的记录。这解释了为什么会出现此错误。要解决它,您需要将其更改为:

@profile = Profile.where(member_id: current_member.id).first

这将返回第一个匹配给定成员id的记录到@profile而不是ActiveRecord::Relation对象。

但是,如果要查找特定记录,则必须使用finder方法。所以更好更清洁的方法是:

@profile = Profile.find_by(member_id: current_member.id)

1
投票

更改profiles_controller.rb中的行

@profile = Profile.find_by(member_id: current_member.id)

当您在where上使用Profile子句时,它将返回一个ActiveRecord::Relation对象数组。但你需要一个@profile对象而不是@profiles对象。多数民众赞成你应该使用find_by方法而不是where条款。


0
投票

我认为问题是你在show方法上的界限

@show_page = params[:id]

您需要指明模型在哪里包含params id

@show_page = Model.find(params[:id]) #=> model is your model which you can using

我认为会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.