1
形成多個枚舉選擇創建形式爲在導軌
<%= 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 %>
模型
class Article < ActiveRecord::Base
enum article_type: [:headline, :news, :editorial, :political, :social, :sports, :food]
scope :by_type, -> { where(article_type: [0..2, 4]) }
end
控制器
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
架構
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
我希望能夠爲每篇文章分配多個枚舉。現在我的表單只接受一個枚舉選擇,我不確定是否必須將表/模式更改爲數組以接受多個枚舉選擇。另外,我前一段時間寫了這段代碼,我不再記得{ where(article_type: [0..2, 4]) }
的含義。