【问题标题】:Undefined method 'about' for nill classnill 类的未定义方法“about”
【发布时间】:2016-08-23 07:01:09
【问题描述】:

我有两张桌子:User 有一张 AccountAccountbelongs_to User。当我想从字段'about'(表Accounts)中获取一些值时,我遇到了nil:NilClass 的问题'undefined methodabout'。挑战在于获取关注者列表并从另一个表中获取他们的头像或“关于”的信息,并将其输出到 View 中。

我在控制器中的方法

 def list_of_follower
   @followers_id = Follow.select("follower_id ").where("followable_id = ?", current_user)
   @followers = User.where("id in (?)", @followers_id)
   @followables_id = Follow.select("followable_id").where("follower_id = ?", current_user)
   @followables = User.where("id in (?)", @followables_id)
end

查看list_of_follower.html.haml

%h1 My followers
 - @followers.each do |f|
  %ul.list-group
    %li.list-group-item
      %p=f.name
      %p=f.account.about
%h1 I'm follower
- @followables.each do |followable|
  %ul.list-group
%li.list-group-item
  %p=followable.name
  %p=followable.account.about

Create_Accounts.rb

class CreateAccounts < ActiveRecord::Migration
  def change
    create_table :accounts do |t|
      t.belongs_to :user, index: true
      t.text :about
      t.timestamps null: false
    end
 end
end

用户.rb

class User < ActiveRecord::Base
 acts_as_followable
 acts_as_follower
 acts_as_liker
 has_one :account
 has_many :posts
 has_many :comments

accepts_nested_attributes_for :account
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

def email_required?
  false
end

def email_changed?
  false
end

 validates :login, :email, uniqueness: true
end

帐户.rb

class Account < ActiveRecord::Base
 belongs_to :user
  mount_uploader :avatar, AvatarUploader
 end

tableUser的内容显示没有问题(工作请求),但是与之关联的table的内容却没有显示,是什么问题?

【问题讨论】:

  • 运行rails console通过user = User.create(&lt;options&gt;)创建一个新用户,运行user.account.nil?,如果答案是真的,新用户没有创建默认帐户,因此你必须建立那。如果是这种情况,我会发布那个答案。
  • 是的,答案是正确的

标签: ruby-on-rails activerecord nested-attributes


【解决方案1】:

我认为,问题在于不是每个用户都有一个帐户。 你可以试试这个:

%p=f.account.try(:about)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    • 2016-06-07
    • 2016-06-30
    • 2021-06-19
    • 2015-01-23
    • 2014-07-14
    相关资源
    最近更新 更多