0
RoR相當新穎,並通過教程工作。不知道爲什麼我得到這個錯誤,因爲我有一個用戶模型,將first_name定義爲可訪問的attr(它表示first_name不是定義的方法,如果我大寫用戶)。未定義的本地變量或方法`用戶
錯誤: 未定義局部變量或方法`用戶」的#<#: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 %>
工作,謝謝! – 2013-03-12 19:03:29
因此,即使方法屬於像用戶這樣的模型,您仍然需要擁有狀態。在呼叫用戶之前,因爲...爲什麼 – 2013-03-12 19:04:11
因爲'self'不是'status'對象。 'status.user'將執行'join'。除非對象不是'self',否則你需要使用'status'。 – codeit 2013-03-12 19:10:11