Ruby on rails 未定义的方法使用Draper decorator链接到编辑

Ruby on rails 未定义的方法使用Draper decorator链接到编辑,ruby-on-rails,draper,Ruby On Rails,Draper,我有一个User和Post模型,它们以一种经典的方式相互关联--用户有很多:Post和Post属于:User。在我的users#show中,我显示了一个用户的个人资料,我还列出了他发表的所有帖子。此外,我想有链接编辑和删除每个帖子尊重。所以,我就这样做了: <% @user.posts.each do |post| %> <h1><%= link_to post.title, post_path(post) %></h1> <% if

我有一个User和Post模型,它们以一种经典的方式相互关联--
用户有很多:Post
Post属于: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 %>
然后,在我的
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=..装饰
,但你在视图中使用了
@user.posts.each{post}
。馈送到该块的对象不会被装饰。只有
@post
是可用的

在您看来,您应该执行类似于
@user.posts.each{raw_post | post=raw_post.decoration}
等操作。显然,使用ERB语法。或者
@user.decordent\u 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
class用户
您可能同时发现了这一点,但这里给其他人一个答案:您在控制器中调用了
@post=..装饰
,但您在视图中使用了
@user.posts.each{post}
。馈送到该块的对象不会被装饰。只有
@post
是可用的

在您看来,您应该执行类似于
@user.posts.each{raw_post | post=raw_post.decoration}
等操作。显然,使用ERB语法。或者
@user.decordent\u 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
class用户
谢谢!您的方法似乎比我的好得多,因为我刚刚将decorator删除到
@user
模型,我想这不能被视为最佳实践:)谢谢!您的方法似乎比我的好得多,因为我刚刚将decorator删除到
@user
模型,我想这不能被视为最佳实践:)