发布评论以发布

时间:2016-04-10 17:43:25

标签: ruby-on-rails ruby

我的Comment模型同时属于PostUserUser模型是自定义的,并通过omniauth进行身份验证)。因此,我无法在_comment.html.erb中管理如何解决错误:它会返回ActionView::Template::Error (undefined method 'avatar_url' for nil:NilClass)。这是代码:

post.rb

has_many :comments, dependent: :destroy

user.rb

has_many: comments, dependent: :destroy
class << self
    def from_omniauth(auth)
        provider = auth.provider
        uid = auth.uid
        info = auth.info.symbolize_keys!
        user = User.find_or_initialize_by(uid: uid, provider: provider)
        user.name = info.name
        user.avatar_url = info.image
        user.profile_url = info.urls.send(provider.capitalize.to_sym)
        user.save!
        user
    end
end

comment.rb

belongs_to :post
belongs_to :user

comments_controller.rb

def new
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create
end

def create
    if current_user
        @post = Post.find(params[:post_id])
        @comment = @post.comments.create(comment_params)
        @comment = current_user.comments.create(comment_params)
    end
    redirect_to post_path(@post)
end

_comment.html.erb

<div>
    <%= link_to image_tag(comment.user.avatar_url, 
         alt: comment.user.name, class: "media-object"),
         comment.user.profile_url, target: '_blank', class: 'pull-left' %>
    <h4 class="media-heading">
        <%= link_to comment.user.name, comment.user.profile_url, target: '_blank' %>
    </h4>
    <p><%= comment.body %></div>
</div>

源代码:https://github.com/AlexNikolaev94/vilenskaya.git

1 个答案:

答案 0 :(得分:2)

我刚刚在你的部分中添加了if语句,你现在可以尝试一下:

<div>
 <% if comment.user.present? %>
  <%= link_to image_tag(comment.user.avatar_url, alt: comment.user.name, class: "media-object"),comment.user.profile_url,target: '_blank', class: 'pull-left' %>
  <h4 class="media-heading">
    <%= link_to comment.user.name, comment.user.profile_url, target: '_blank' %>
  </h4>
  <p><%= comment.body %></div>
 <% end %> 
</div>
相关问题