为帖子创建Post_category选择我的帖子,收集post_category

时间:2016-04-19 20:06:00

标签: ruby-on-rails methods controller

我创建了一个post_category表来为特定帖子添加一个类别。

例如,我创建了post_categories作为国家,像日本或中国。我想创建来自日本或中国等国家的文化或模式的帖子。我只专注于post_categories,因为现在和以下的国家是我所做的代码。

我创建了这个PostCategory,这里是迁移和模型

 create_table "post_categories", force: :cascade do |t|
    t.string   "name"
    t.string   "description"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

class PostCategory < ActiveRecord::Base
  has_many :posts, dependent: :destroy

  NAMES = ["Japon", "Chine", "Corée du Sud", "Moyen Orient", "Indien"]
  validates :name, inclusion: { in: PostCategory::NAMES, allow_nil: false }
end

我使用Post外键创建了PostCategory,这里是迁移和模型

  create_table "posts", force: :cascade do |t|
    t.string   "cover"
    t.string   "subtitle"
    t.string   "title"
    t.text     "introduction"
    t.text     "body"
    t.text     "conclusion"
    t.string   "tag"
    t.string   "source"
    t.string   "link"
    t.integer  "user_id"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false
    t.integer  "post_category_id"
  end

class Post < ActiveRecord::Base
  belongs_to :user

  belongs_to :post_category, dependent: :destroy

  TAGS = ["Design", "Mode", "Tendance", "Life-Style", "Tradition", "Gastronomie", "Insolite", "Technologie"]
  validates :tag, inclusion: { in: Post::TAGS, allow_nil: false }

  mount_uploader :cover, ImageUploader
end

我想用简单的表单集创建一个类别,我希望我会在post show#view上显示

以下是post_categories controller

class PostCategoriesController < ApplicationController
   # before_action :set_post_category, only: [:show, :new, :create, :destroy]

  def show
    @post_category = PostCategory.find(params[:id])
  end

  def index
    @post_categories = PostCategory.all
  end

  def create
    @post_category = post_categories.new(post_category_params)
    if @post_category.save
      redirect_to @post
    else
      render 'post_categories/show'
    end
  end

  def new
    @post_category = PostCategory.new
  end

  def edit
  end

  def update

  end

  def destroy
    @post_category = PostCategory.find(params[:id])
    @post_category.destroy
    redirect_to post_path(@post)
  end

  private

  # def set_post
  #   @post = Post.find(params[:post_id])
  # end

   def find_post_category
    @post_category = PostCategory.find(params[:id])
  end

  def post_category_params
    params.require(:post_category).permit(:name, :description)
  end
end

这是posts controller

class PostsController < ApplicationController

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

  def index
    @posts = Post.all
  end

  def show
    # @alert_message = "Vous lisez #{@post.title}"
  end

  def new
    # if current_user and current_user.admin?
      @post = Post.new
    # else
    #   redirect_to posts_path
    # end
  end

  def create
    # if current_user and current_user.admin?
     @post = @post_category.posts.new(post_params)
      #@post = current_user.posts.new(post_params)
      if @post.save
        redirect_to @post
      else
        render :new
      end
    # else
    #   render 'shared/404.html.erb'
    # 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 :back
  end

  private

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

  def set_post_category
    @post_category = PostCategory.find(params[:post_category_id])
  end

  def post_params
    params.require(:post).permit(:title, :subtitle, :introduction, :body, :cover, :tag, :post_category_id)

  end
end

我不知道我可以创建哪些观点以及如何调用post new#view,因为我已经配置了这样的路线,我需要post_category_id

resources :post_categories do
    resources :posts
  end

我必须在path

之后使用此功能
 post_category_posts GET      /post_categories/:post_category_id/posts(.:format)          posts#index
                              POST     /post_categories/:post_category_id/posts(.:format)          posts#create
       new_post_category_post GET      /post_categories/:post_category_id/posts/new(.:format)      posts#new
      edit_post_category_post GET      /post_categories/:post_category_id/posts/:id/edit(.:format) posts#edit
           post_category_post GET      /post_categories/:post_category_id/posts/:id(.:format)      posts#show
                              PATCH    /post_categories/:post_category_id/posts/:id(.:format)      posts#update
                              PUT      /post_categories/:post_category_id/posts/:id(.:format)      posts#update
                              DELETE   /post_categories/:post_category_id/posts/:id(.:format)      posts#destroy
              post_categories GET      /post_categories(.:format)                                  post_categories#index
                              POST     /post_categories(.:format)                                  post_categories#create
            new_post_category GET      /post_categories/new(.:format)                              post_categories#new
           edit_post_category GET      /post_categories/:id/edit(.:format)                         post_categories#edit
                post_category GET      /post_categories/:id(.:format)                              post_categories#show
                              PATCH    /post_categories/:id(.:format)                              post_categories#update
                              PUT      /post_categories/:id(.:format)                              post_categories#update
                              DELETE   /post_categories/:id(.:format)                              post_categories#destroy

我想在show#view post上添加该类别,并创建一个多帐户访问权限,以查找添加到特定类别的帖子。谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

你设置关系的方式因为有一个很大的缺陷 - 一个帖子只能属于一个类别,因为id存储在posts表中。

相反,你通常会使用多对多的关系:

class Post < ActiveRecord::Base
  has_many :categories, :categories
  has_many :post_categories
end

class Category < ActiveRecord::Base
  has_many :posts
  has_many :posts, through: :categories
end

class Categorization < ActiveRecord::Base
  belongs_to :post
  belongs_to :category
  validates_uniqueness_of :category_id, scope: :post_id
end

此处categorizations表充当链接PostCategory的联接表 - 帖子可以包含任意数量的类别,反之亦然。

增加:

要创建连接模型和迁移到创建表,您可以执行以下操作:

rails g model Categorization post:belongs_to category:belongs_to

默认情况下,在生成器中使用属于为post_idcategory_id创建外键。

您可能还希望在迁移中添加复合唯一性约束。

def change 
  # ...
  add_index(:categorizations, [:post_id, :category_id], unique: true)
end

您使用CategoriesController在正确的轨道上,但我不会使用嵌套路线来创建帖子。相反,您可能只想使用普通的旧rails控制器,让用户通过复选框选择类别:

<%= form_for(@post) do |f| %>
  <%= f.collection_check_boxes :category_ids, Category.all, :id, : name %>
<% end %>

然后,您可以将category_ids参数添加到白名单中:

  def post_params
    params.require(:post)
          .permit(:title, :subtitle, :introduction, 
                  :body, :cover, :tag, category_ids: []
                 )

  end

奇怪的category_ids: []语法是因为我们想要允许一组标量值。

按ID查询某个类别的帖子可以这样完成:

Post.joins(:categories).where(category: 1)

您甚至可以通过传递数组来选择多个类别:

Post.joins(:categories).where(category: [1, 2, 3])

要从视图中将它连接在一起,您可以使用链接(对于单个类别)或表单(是表格可用于GET)以及复选框或选择。

处理文本输入有点棘手。一个天真的实现将是:

Post.joins(:categories).where(category: { name: params[:search_query] })

然而,用户输入必须完全匹配。有几个宝石为活动记录提供搜索功能。但是我会等待这个功能,直到你有更多的经验,因为它可能很难实现。

请参阅: