我有两个表:User
有一个Account
, Account
belongs_to User
。当我想从字段'about
'(表Accounts
)获得一些值时,我的问题'undefined method
about
'为nil:NilClass
'。我们面临的挑战是获取关注者列表,并从另一个表中获取他们的头像或信息“about”并将其输出到View中。未定义的方法'约'为nill类
我的控制器方法
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
内容显示没有问题(工作请求),但不会显示与之相关联的表的内容,请问是什么问题?
运行'轨console'通过创建用户'= User.create新用户()',运行''user.account.nil,如果答案是真的,?新用户没有创建默认帐户,因此您必须创建该帐户。如果是这种情况,我会发布这个答案。 –
amingilani
是的,回答是真的 – Gaka