在 Rails 中向文章添加类别时出现问题



我在以简单形式将类别添加到文章中时遇到问题。类别显示在simple_form_for中,但在创建文章时category_id不归因于文章!(参数?

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

用于创建文章的文章控制器

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

以及我使用 f.association 的simple_form_for(它正确显示了不同的类别(

<%= 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 %>

我认为我的数据库还可以,因为我可以使用控制台将类别归因于文章,但我被困在这种形式中。任何帮助将不胜感激。谢谢爱德华

编辑

这是我的迁移。有什么不对吗?

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

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

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

最新更新