I have an issue adding Categories to article in my simple form. The categories are showing up in the simple_form_for but the category_id is not attributed to the article when creating it ! (params ?)
Tx for your help !
I have created two models
class Category < ApplicationRecord
has_many :articles
end
class Article < ApplicationRecord
belongs_to :category
has_attachments :photos, maximum: 2
end
and a foreign key between them
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
The Articles controller to create an article
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
and the simple_form_for where I used f.association (which shows correctly the different categories)
<%= 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 %>
I think my db is ok because I can attribute a category to an article with the console but I m stuck in this form. Any help would be much appreciated. Thx Edouard
EDIT
Here is my migration. Anything wrong?
class AddCategoryReferenceToArticles < ActiveRecord::Migration[5.0]
def change
add_reference :articles, :category, foreign_key: true, index: true
end
end
Adding category_id
in article_params
should solve the issue
def article_params
params.require(:article).permit(:title, :card_summary, :summary, :category_id, photos: [])
end