首页 文章

在Rails中向Article添加类别的问题

提问于
浏览
0

我有一个问题,以简单的形式向文章添加类别 . 类别显示在simple_form_for中,但category_id在创建时不归因于文章! (params?)

Tx为您提供帮助!

我创造了两个模型

class Category < ApplicationRecord
  has_many :articles
end

class Article < ApplicationRecord
  belongs_to :category
  has_attachments :photos, maximum: 2
end

和他们之间的外键

create_table "articles", force: :cascade do |t|
  t.string   "title"
  t.text     "body"
  t.datetime "created_at",   null: false
  t.datetime "updated_at",   null: false
  t.string   "card_summary"
  t.text     "summary"
  t.integer  "category_id"
  t.index ["category_id"], name: "index_articles_on_category_id",      using: :btree
end

Articles控制器创建一篇文章

def new
  @article = Article.new
end

def create
  @article = Article.new(article_params)
  if @article.save
    redirect_to article_path(@article)
  else
    render :new
  end
end

private

def article_params
  params.require(:article).permit(:title, :card_summary, :summary, :body, photos: [])
end

和simple_form_for我使用f.association(正确显示不同的类别)

<%= simple_form_for @article do |f| %>
  <%= f.input :title %>
  <%= f.input :card_summary %>
  <%= f.input :summary %>
  <%= f.input :photos, as: :attachinary %>
  <%= f.input :body %>
  <%= f.association :category %>

  <%= f.submit "Soumettre un article", class: "btn btn-primary" %>
<% end %>

我认为我的数据库是可以的,因为我可以将一个类别归因于一个带有控制台的文章,但我陷入了这种形式 . 任何帮助将非常感激 . 谢谢爱德华

EDIT

这是我的迁移 . 哪里不对了?

class AddCategoryReferenceToArticles < ActiveRecord::Migration[5.0]
  def change
    add_reference :articles, :category, foreign_key: true, index: true
  end
end

1 回答

  • 0

    article_params 中添加 category_id 应该可以解决问题

    def article_params
      params.require(:article).permit(:title, :card_summary, :summary, :category_id, photos: [])
    end
    

相关问题