我一直试图弄清楚这一段时间,但却无法让它正常工作。我正在使用设计,我正在尝试显示用户的用户名,该用户评论了一个名为“pit”的对象,这与博客帖子基本相同,但具有更多功能。最初我发现它没有在我的评论模型中保存用户ID,但我修复了它,现在它只是渲染上面的内容。这里的所有搜索都得到了一些帮助但没有完整的解决方案。欢迎任何和所有帮助以及批评。感谢。
该页面呈现的是下面而不是名称
"<User: 0x00000105929950>"
我有一个名为_comment.html.erb的部分代码应该在
下面呈现<p>
<strong>Comment:</strong>
<%= comment.body %>
<%= comment.user %>
</p>
<p>
<%= link_to 'Destroy Comment', [comment.pit, comment],
method: :delete,
data: { confirm: 'Are you sure?' } %>
</p>
评论控制器:
class CommentsController < ApplicationController
def create
@pit= Pit.find(params[:pit_id])
@comment = @pit.comments.build(comments_params)
@comment.user = current_user
@comment.save
redirect_to pit_path(@pit)
end
def destroy
@pit = Pit.find(params[:pit_id])
@comment = @pit.comments.find(params[:id])
@comment.destroy
redirect_to pit_path(@pit)
end
def show
end
private
def comments_params
params.require(:comment).permit(:body, :user_id)
end
端
坑控制器
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 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
Pit Model
class Pit < ActiveRecord::Base
has_many :comments
belongs_to :user
end
评论模型
class Comment < ActiveRecord::Base
belongs_to :pit
belongs_to :user
end
答案 0 :(得分:2)
你需要写
comment.user.name
而不是
comment.user