RoR相当新,并通过教程工作。不知道为什么我会收到此错误,因为我有一个用户模型将first_name定义为可访问的attr(如果我将用户大写,则说first_name不是定义的方法)。
错误: 未定义的局部变量或方法`user'for#<#:0x007fdb75963478> 提取的来源(第9行):
6:
7: <% @statuses.each do |status| %>
8: <div class ="status">
9: <strong><%= user.first_name %></strong>
10: <p><%= status.content %></p>
11: <div class ="meta">
12: <%= link_to time_ago_in_words(status.created_at) + " ago", status %>
我的代码: 用户模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me,
:first_name, :last_name, :profile_name
# attr_accessible :title, :body
validates :first_name, presence: true
validates :last_name, presence: true
validates :profile_name, presence: true, uniqueness: true,
format: {
with: /a-zA-Z0-9_-/,
message: 'Must be formatted correctly.'
}
def full_name
return first_name + " " + last_name
end
has_many :statuses
end
Index.html.erb:
<div class="page-header">
<h1>All of the statuses</h1>
</div>
<%= link_to "Post a new Status", new_status_path, class: "btn btn-success" %>
<% @statuses.each do |status| %>
<div class ="status">
<strong><%= user.first_name %></strong>
<p><%= status.content %></p>
<div class ="meta">
<%= link_to time_ago_in_words(status.created_at) + " ago", status %>
<span class="admin">
| <%= link_to "Edit", edit_status_path(status) %> |
<%= link_to "Delete", status, method: :delete, data: {confirm: "Are you sure you wanna delete this status"} %>
</span>
</div>
</div>
<% end %>
答案 0 :(得分:2)
在线#9
,它应该是:
<%= status.user.first_name %>
假设belongs_to :user
模型中有Status
。