在 Rails 中为多个枚举选择创建表单



Form

<%= 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]) }是什么意思了。

枚举类型的列只能分配一个值。这就是他们的重点。如果需要存储多个值,则可能表示数据需要重新建模。

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)

最新更新