如何使用hmt在rails应用程序上创建类别?

时间:2015-03-09 19:13:44

标签: ruby-on-rails

我试图在我的博客中创建一个类别。我有一个帖子和类别模型,帖子可能有些类别。例如:运动,动物,政策等。

post.rb

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :post_categories
  has_many :categories, through: :post_categories
  accepts_nested_attributes_for :categories
end

category.rb

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

和第三个模型post_category.rb

class PostCategory < ActiveRecord::Base
  belongs_to :post
  belongs_to :category
end

post_params类方法post.rb

def post_params
  params.require(:post).permit(:title, :body, :description, :user,
                               :categories_attributes [:name,
                                                            :category_id])

当我尝试创建表单时,我不明白如何制作表单

h2 Create
    = form_for @post do |f|
      = f.text_field :title, placeholder: 'Title', class: "form-control"
      = f.text_area :body, :class => "redactor", :rows => 40, :cols => 120
      = f.fields_for :categories do |c|
        = c.check_box :category
      .pull-right
        = f.submit "Send", class: "btn btn-success"

如何制作?

1 个答案:

答案 0 :(得分:1)

使用HTML标记将%添加为%h2

%h2 Create
= form_for @post do |f|
  = f.text_field :title, placeholder: 'Title', class: "form-control"
  = f.text_area :body, :class => "redactor", :rows => 40, :cols => 120
  = f.fields_for :categories do |c|
    = c.check_box :category
  .pull-right
    = f.submit "Send", class: "btn btn-success"

你应该可以做这样的事情,对你的第二个问题

不太确定
= f.fields_for :categories, category do |category| 
    = check_box_tag "post[category_ids][]", category.id, @post.categories.include?(category)`