我试图在索引视图中使用视图助手,并且我一直在:
NoMethodError in Posts#index
undefined method 'content' for #<SpudPost::ActiveRecord_Relation:0x007fa573bf4c60>
我在我的帮手中有以下内容:
module TinyPostsHelper
def post_truncate(&block)
truncate(@posts.content,
length: 500,
omission: '...') {
link_to 'Something', post_path(posts.url_name)
}
end
然后在我的控制器中我有:
class TinyPostsController < ApplicationController
respond_to :json, :html
before_action :load_post, except: [:index]
before_action :new_comment, only: [:post_partial, :post_comments]
def index
@return_to = tiny_posts_path
@posts = TinyPost.ordered.published.paginate(page: params[:page], per_page: params[:per_page] || 20)
@posts = TinyPost::Search.run(@posts, params).result if params[:search]
end
def post_partial
render partial: 'post'
end
def show
if request.xhr?
render json:
@post.as_json(only: [:id], methods: [:cover_url],
include: { dream_books: { only: :id } }
)
else
new_comment
render :show
end
end
def create_comment
operation = TinyPost::CreateComment.run(comment_params, @post, current_user)
respond_with operation.result
end
def post_comments
render partial: 'post_comments', locals: { post: @post }
end
private
def load_post
@post = TinyPost.find_by!(url_name: params[:id])
end
def comment_params
params.require(:dream_post_comment).permit(:content)
end
def new_comment
@comment = DreamPostComment.new
end
end
然后在我看来,我正在使用
<%= post_truncate%>
我可以使用字符串插值,最终结果非常好,但问题是我不明白为什么我收到关于内容不是方法的消息。
答案 0 :(得分:2)
.content
无法在整个ActiveRecord关系上调用,只能在一个帖子记录中调用。你应该做点什么
@posts.each do |post|
truncate(posts.content,
length: 500,
omission: '...') {
link_to 'Something', post_path(posts.url_name)
}
end