我有两张表:User
有一个Account
,Account
belongs_to User
。当我想从字段“about
”(表Accounts
)中获取某些值时,我对undefined method
'有一个问题“about
nil:NilClass
”。挑战在于获取关注者列表并从另一个表中获取他们的头像或“关于”的信息,并在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
User.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
Account.rb
class Account < ActiveRecord::Base
belongs_to :user
mount_uploader :avatar, AvatarUploader
end
表User
内容显示没有问题(工作请求),但与之关联的表的内容没有显示,有什么问题?
答案 0 :(得分:1)
我认为,问题不是每个用户都有帐户。 你可以试试这个:
%p=f.account.try(:about)