我正在尝试列出与posts控制器无关的视图中current_user的所有帖子。我试过这样做,但似乎无法绕过它
posts_controller.rb
class PostsController < ApplicationController
before_action :authenticate_user!
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.all
@posts = Post.paginate(:page => params[:page], :per_page => 5, :order => 'id DESC')
end
def show
end
def new
@post = Post.new
end
def edit
end
def create
@post = Post.new(post_params)
@post.email = current_user.username
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: @post }
else
format.html { render action: 'new' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @post.update(post_params)
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
#protect_from_forgery with: :null_session #i added this from SO!!!!!!!!!!!!!!!!!!
before_filter :configure_permitted_parameters, if: :devise_controller?
helper_method :mypost
def mypost
@mypost = Post.all
@mypost = Post.paginate(:page => params[:page], :per_page => 5, :order => 'id DESC')
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :username
devise_parameter_sanitizer.for(:account_update) << :username
end
end
在新网站的视图中
<% @mypost.each do |mypost| %>
<%= link_to post do %>
<div id="rectmine">
<h1><%= post.title %></h1>
<p><%= post.author %><p>price: <%= post.price %></p> location: <%= post.school %>
<hr style="width: 505px;">
<% end %>
<% if current_user.email == post.email %>
<p>This is your post! Feel free to edit or delete it. -> </p>
<%= link_to 'Edit', edit_post_path(post) %>
<%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
<% end %>
答案 0 :(得分:1)
从助手返回新变量。
helper_method :get_post_paginate
def get_post_paginate
@mypost = Post.paginate(:page => params[:page], :per_page => 5, :order => 'id DESC')
@mypost
end
并在视图中使用方法调用
<% get_post_paginate.each do |mypost| %>
答案 1 :(得分:1)
为什么不将代码放在要调用的控制器中。例如,如果您调用NoPostsController的索引操作,则可以将代码放在该操作中,它应该可以正常工作。在帮助器中放置查询对我来说似乎很奇怪,我认为该逻辑不属于那里。
您唯一想要的是每个控制器都可以访问当前用户。