【问题标题】:Issue Adding Category to Article in Rails在 Rails 中向文章添加类别的问题
【发布时间】:2017-06-14 13:50:02
【问题描述】:

我在以简单形式向文章添加类别时遇到问题。 类别显示在 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

【问题讨论】:

  • 不在你的参数.permit(:title, :card_summary, :summary, :body, photos: [],也不在你的表单中,但是在你的迁移中出现category_id
  • 这是我的迁移

标签: ruby-on-rails associations strong-parameters simple-form-for


【解决方案1】:

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

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

【讨论】:

  • 就是它!非常感谢(几乎为此烧毁了我的日常大脑!);)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 2012-02-24
  • 2022-01-13
相关资源
最近更新 更多