向rails 4中的帖子添加类别

时间:2014-03-06 00:01:04

标签: ruby-on-rails ruby ruby-on-rails-4 categories

我有一个模型资源,当我创建一个新条目时,我希望能够为它分配一个类别。代码设置如下:

Resource.rb

has_many :categories

category.rb

has_many_and_belongs_to :resources

(资源)_form.html.erb(以及其他资源字段)

<%= form_for @resource do |f| %>
  <%= f.select :category, Category.all, :prompt => "Category" %>
<%= end %>

categories_controller.rb

class CategoriesController < ApplicationController
    def new
        @category = Category.new
    end

    def edit
        @category = Category.find(params[:id])
    end

    def create
      @category = Category.new(category_params)

      @category.save
      #redirect_to @category
    end

    def update
      @category = Category.find(params[:id])

      #if @category.update(params[:category].permit(:category_params))
      #  redirect_to @category
      #else
      #  render 'edit'
      #end
    end

    def destroy
      @category = Category.find(params[:id])
      @category.destroy

      #redirect_to categorys_path
    end

    private
      def category_params
        params.require(:category).permit(:name)
      end 
end

只有4个左右的类别,它们不会改变。我只需要在创建资源条目时通过下拉列表分配类别,并列出特定类别下的条目。

现在,我在尝试查看资源/新版时收到错误“未定义方法'类别'。

任何易于理解(rails初学者)帮助表示赞赏

2 个答案:

答案 0 :(得分:1)

首先在资源模型上还需要has_and_belongs_to_many

对于输入,您需要添加参数multiple: true

有关详情Rails 3: Multiple Select with has_many through associations

,请参阅此问题的答案

您需要在表单上使用类别而不是类别。

答案 1 :(得分:0)

你想要ActsAsTaggableOn!

https://github.com/mbleigh/acts-as-taggable-on

这个辉煌的宝石为您解决了类别问题。但是,这不是您要问的问题......您收到错误是因为您没有正确设置关联。

  • 首先,您需要在两个型号上使用has_and_belongs_to_many。
  • 第二个问题,您需要将选择字段更改为:categories
  • 第三个问题,您需要在表单中包含multiple: true以允许多个选择。

<%= f.collection_select :category_ids, Category.all, :id, :name, :prompt => "Category", :multiple => true %>

我强烈建议您查看ActsAsTaggableOn因为文档太棒了。它还有一个RailsCast

相关问题