Ruby on rails 显示数字而不是用户名的用户注释
我一直想弄明白这一点,但就是不能让它正常工作。我正在使用Desive,我试图显示一个用户的用户名,该用户对一个名为“pit”的对象发表了评论,这个对象基本上与博客文章相同,但还有一些其他功能。最初我发现它没有在我的评论模型中保存用户id,但我修复了这个问题,现在它只是呈现上面的内容。这里的所有搜索都提供了一些帮助,但没有完整的解决方案。欢迎任何和所有的帮助加上批评。谢谢 页面将在下面呈现此内容,而不是名称Ruby on rails 显示数字而不是用户名的用户注释,ruby-on-rails,devise,Ruby On Rails,Devise,我一直想弄明白这一点,但就是不能让它正常工作。我正在使用Desive,我试图显示一个用户的用户名,该用户对一个名为“pit”的对象发表了评论,这个对象基本上与博客文章相同,但还有一些其他功能。最初我发现它没有在我的评论模型中保存用户id,但我修复了这个问题,现在它只是呈现上面的内容。这里的所有搜索都提供了一些帮助,但没有完整的解决方案。欢迎任何和所有的帮助加上批评。谢谢 页面将在下面呈现此内容,而不是名称 "<User: 0x00000105929950>" 结束 用户控制器 d
"<User: 0x00000105929950>"
结束
用户控制器
def index
@pit = Pit.all
@user = User.find_by(params[:id])
@pit = @user.pits
@pits = Pit.order('created_at DESC')
end
def create
@user = current_user
@pit = current_user.pits.create(pit_params)
if @pit.save
redirect_to @pit
else
render 'new'
end
end
def show
@pit = Pit.find(params[:id])
end
def edit
end
def update
end
private
def pit_params
params.require(:pit).permit(:topic, :summary, :image, :video_url, :author, :user_id)
end
class UsersController < ApplicationController
before_filter :authenticate_user!
def index
@users = User.all
authorize User
end
def show
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
authorize @user
if @user.update_attributes(secure_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
def destroy
user = User.find(params[:id])
authorize user
user.destroy
redirect_to users_path, :notice => "User deleted."
end
private
def secure_params
params.require(:user).permit(:role)
end
end
class UsersController“用户已更新。”
其他的
将\重定向到用户\路径:警报=>“无法更新用户。”
结束
结束
def销毁
user=user.find(参数[:id])
授权用户
用户破坏
将\重定向到用户\路径:notice=>“用户已删除。”
结束
私有的
def安全参数
参数require(:用户).permit(:角色)
结束
结束
用户模型
class User < ActiveRecord::Base
has_many :pits
has_many :comments
enum role: [:user, :vip, :admin]
after_initialize :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :user
end
def name
name = first_name + ' ' + last_name
end
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
class用户:新建记录?
def set_默认_角色
self.role | |=:用户
结束
定义名称
姓名=名+''+姓
结束
#包括默认设计模块。其他可供选择的项目包括:
#:可确认、:可锁定、:超时和:全授权
设计:数据库可验证,可注册,
:可恢复,:可记忆,:可跟踪,:可验证
结束
坑模型
class Pit < ActiveRecord::Base
has_many :comments
belongs_to :user
end
class-Pit
注释模型
class Comment < ActiveRecord::Base
belongs_to :pit
belongs_to :user
end
class注释
您需要编写
comment.user.name
而不是
comment.user
这就是用户对象。你需要显示一个特定的属性,比如user.name。你能试试
或
吗?是的,邦格斯,这很有效。谢天谢地,我曾经尝试过pixelearth,但它成功了。我一定是在修理模型之前试过的。谢谢!请记住,用户是一个关联(对象实例),而不是真正的可打印值。您看到该输出是因为:to_s被称为(我认为,是从继承链的某个位置继承的)。很高兴知道。我在这里还是个新手,所以我真的很想弄清楚在我建造这个东西的时候这里发生了什么。谢谢你的信息。
comment.user.name
comment.user