我有一个User和Post模型,它们以经典方式彼此关联-User has_many :posts
和Post belongs_to :user
。在我的users#show
,我在其中显示用户的个人资料,还列出了他所做的所有帖子。另外,我想提供一些链接来分别编辑和删除每个帖子。因此,我弥补了这一点:
<% @user.posts.each do |post| %>
<h1><%= link_to post.title, post_path(post) %></h1>
<% if @user == current_user %>
<%= link_to 'Edit', edit_post_path(post) %>
<%= link_to 'Delete', post_path(post), method: :delete %>
<% end %>
<% end %>
但是肯定将这种逻辑放在视图中会导致混乱,因此我决定使用Draper并为此编写装饰器。当我们要检查权限posts#edit
和posts#delete
方法时,我想出了Post模型的装饰器,并尝试在中使用它PostsController
。它去了:
class PostDecorator << Draper::Decorator
delegate_all
def link_to_edit
if object.user == current_user
h.link_to 'Edit', h.edit_post_path(object)
end
end
def link_to_delete
if object.user == current.user
h.link_to 'Delete', h.post_path(object), method: :delete
end
end
end
然后,在我的PostsController
:
# ... class definition
before_action :set_post, only: [:show, :edit, :update, :destroy]
# ... other controller methods
def edit; end
def update
if @post.update(post_params)
@post.save
redirect_to post_path(@post)
else
render 'edit'
end
end
def destroy
@post.destroy
redirect_to feed_path
end
private
# Using FriendlyId gem to have neat slugs
def set_post
@post = Post.friendly.find(params[:id]).decorate
end
但是每次我尝试使用他的帖子列表,使用新助手<%= post.link_to_delete %>
以及<%= post.link_to_edit %>
不带条件的混乱来呈现用户个人资料时,它只会向我返回以下错误:
我究竟做错了什么?
您可能同时想出了这一点,但对于其他人来说,这是一个答案:您正在调用@post = ....decorate
控制器,但正在@user.posts.each { |post| ... }
视图中使用。馈送到该块的对象未装饰。只有@post
。
在您看来,您应该做类似的事情@user.posts.each { |raw_post| post = raw_post.decorate }
。显然,具有ERB语法。或@user.decorated_posts.each ...
在哪里
class User < ActiveRecord::Base
...
def decorated_posts
# this will load every post associated with the user.
# if there are a lot of them you might want to only load a limited scope of them
posts.map(&:decorate)
end
...
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句