FormularErstellen Formular für mehrere Aufzählungs Auswahl Schienen
<%= form_for :article, url: articles_path, html: {multipart: true } do |f| %>
<p>
<%= f.label :source %><br>
<%= f.text_field :source %>
</p>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :artwork %><br>
<%= f.text_field :remote_artwork_url %>
</p>
<%= f.select :article_type, Article.article_types.keys, {}, class: 'article-article_type-select' %>
<p>
<%= f.submit %>
</p>
<% end %>
Modell
class Article < ActiveRecord::Base
enum article_type: [:headline, :news, :editorial, :political, :social, :sports, :food]
scope :by_type, -> { where(article_type: [0..2, 4]) }
end
-Controller
class ArticlesController < ApplicationController
def new
if current_user.admin != true
flash[:danger] = "You are not permitted to sumbit articles!"
redirect_to root_url
else
@article = Article.new
end
end
def show
@article = Article.approved.find(params[:id])
end
def create
if current_user.admin != true
redirect_to root_url
else
@article = current_user.articles.build(article_params)
@article.save
if @article.errors.any?
flash[:danger] = "Article failed!"
redirect_to 'new_article_path'
else
flash[:success] = "Article created!"
redirect_to new_article_path
end
end
end
def index
@articles = Article.approved.all
end
private
def article_params
params.require(:article).permit(:artwork, :source, :title, :remote_artwork_url, :article_type)
end
end
Schema
create_table "articles", force: :cascade do |t|
t.string "title"
t.string "source"
t.string "artwork"
t.integer "article_type"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "approved", default: false
end
Ich möchte jedem Artikel mehrere enum zuweisen können. Momentan akzeptiert mein Formular nur eine Enum-Auswahl und ich bin mir nicht sicher, ob ich die Tabelle/das Schema in ein Array ändern muss, um mehrere Enum-Selektionen zu akzeptieren. Außerdem habe ich diesen Code vor einer Weile geschrieben und ich erinnere mich nicht mehr daran, was { where(article_type: [0..2, 4]) }
bedeutet.