Rails应用程序中的Undefined方法问题

时间:2016-12-09 17:52:55

标签: ruby-on-rails devise

我正在Rails中构建一个应用程序。我有一个名为“Users”的表和一个名为“Profiles”的表。每个用户都有_个人资料。每个配置文件都属于一个用户。我正在尝试使用profile_controller的索引页面。我想让每个用户个人资料按照他们登录的顺序显示。但我有更多基本问题。首先,我有

 @users = All.users

在索引操作中定义。每个“配置文件”都有一个“名称”属性。在索引视图中,我尝试通过@users

访问此属性
  <% @users.each do |u| %>
    <%= u.profile.name %> 
  <% end %>

这为nil:NilClass提出了这个错误“undefined method`name'。”请注意,这确实有效:

 <% @users.each do |u| %>
    <%= u.last_sign_in_at %> 
  <% end %>

我想通过“Users”中的“last_sign_in_at”Devise属性来组织名称,否则我只是直接使用profile对象。我还没有开始订购。有人可以帮忙吗?我希望能够通过@users实例变量访问配置文件属性。这是我的架构:

create_table "profiles", force: :cascade do |t|
t.datetime "created_at",         null: false
t.datetime "updated_at",         null: false
t.integer  "age"
t.string   "status"
t.string   "location"
t.string   "bio"
t.string   "primary_instrument"
t.string   "second_instrument"
t.string   "third_instrument"
t.string   "name"
t.integer  "user_id"
t.string   "looking_for"
end

create_table "users", force: :cascade do |t|
t.string   "email",                  default: "", null: false
t.string   "encrypted_password",     default: "", null: false
t.string   "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer  "sign_in_count",          default: 0,  null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string   "current_sign_in_ip"
t.string   "last_sign_in_ip"
t.datetime "created_at",                          null: false
t.datetime "updated_at",                          null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true  

1 个答案:

答案 0 :(得分:2)

您能否向我们展示用户和个人资料模型? 出现错误是因为一个或多个用户没有个人资料,您还可以使用u.profile.try(:name)或(我认为最差)u.profile.name if user.profile.present?

等方法

关于用户配置文件属性,这里有关于此主题{gre}的重要文章,或者如果您不想使用它,您可以执行类似

的操作
#user Model
def name
  profile.try(:name)
end