表格
<%= 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]) }
的含义。
答案 0 :(得分:1)
枚举类型的列只能分配一个值。这就是他们的观点。如果需要存储多个值,则可能表示数据需要重新构建。
scope :by_type, -> { where(article_type: [0..2, 4]) }
以上查询获取所有类型为0或1或2或4的文章。它会产生以下查询
SELECT "articles".* FROM "articles" WHERE ("articles"."id" = 4 OR "articles"."id" BETWEEN 0 AND 2)