Rails - 在静态页面中列出模型的记录

时间:2015-01-04 22:26:25

标签: ruby-on-rails activerecord

我正在尝试将模型的记录(列出所有记录,如Posts.all)调用到绑定到另一个控制器的视图。

所以,我想达到Posts_controller的索引操作,其中包含我想要访问的.all列表和.group_by列表,并将它们列在Pages_controller中列出的静态页面中(命名为yonetim)

这仅用于列出管理员视图的帖子(如活动管理员中的列表)。

我认为,我不需要发布任何代码,因为问题很抽象,但如果需要,我会编辑问题。

*编辑以澄清*

这是我的posts_controller.rb

class PostsController < ApplicationController

    before_action :find_post, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, except: [:index, :show]

    load_and_authorize_resource

    def index
        @posts = Post.all.order('postdate DESC')
        @posts_by_month = @posts.group_by { |post| post.postdate.strftime('%m - %Y')}
    end

    def show
    end

    def new
        @post = current_user.posts.build
    end

    def create
        @post = current_user.posts.build(post_params)

        if @post.save
            redirect_to @post
        else
            render 'new'
        end
    end

    def edit
    end

    def update
        if @post.update(post_params)
            redirect_to @post
        else
            render 'edit'
        end
    end

    def destroy
        @post.destroy
        redirect_to root_path
    end

    private

    def post_params
        params.require(:post).permit(:id, :title, :body, :postdate)
    end

    def find_post
        @post = Post.find(params[:id])
    end

end

可以看出它是一个基本的博客应用程序。到达root_path的访问者(帖子#index routed)可以根据月份和年份的分组查看帖子记录。

我想要添加的是从我为管理界面创建的静态页面中获取新的,编辑destroy和index。@ posts(类似于活动的Admin gem)。

**这是pages_controller.rb **

class PagesController < ApplicationController
    def yonetim
    end
end

所以,当我点击/ yonetim(路由到获取#yonetim页面)时,我希望用户看到posts控制器的索引操作,链接到新的,显示,编辑和销毁记录。

***系统还设有admin boolean和cancan,因此如果用户未登录或没有管理员使用权限,则会将他们移至root_path,但有例外。

我的问题在于,我已经尝试了几乎所有内容来列出页面/ yonetim视图或pages_controller.rb yonetim方法中的帖子#index方法的@posts记录。

这样我就可以在管理员视图中列出它们并与它们一起解决。

如果需要其他任何内容,请告诉我。

提前致谢, 穆斯塔法

1 个答案:

答案 0 :(得分:0)

pages#yonetim的多个选项:

  1. 只需重定向到'posts #index'
  2. 分配视图变量(@posts@posts_by_month),如posts#index和渲染模板posts/index
  3. 分配视图变量(@posts@posts_by_month),如posts#index和渲染模板pages/index(本例中为默认视图)。
  4. 前两个选项的缺点是所有链接(new / edit / destroy)都将链接到PostsController而不是PagesController,因为您正在重新使用这些视图为PostsController创建。