Rails: 保存country_select到数据库

Rails: Save country_select to database

我正在制作一个用户可以选择国家/地区的表单,然后会显示选择 show.html.erb。

我已经在我的表单中添加了 country_select 这样的

<div class="col-md-4">
  <div class="form-group">
    <%= f.country_select :country %>
 </div>

我的模型 article.rb 看起来像这样:

class Article < ActiveRecord::Base
    belongs_to :author
    has_many :article_article_categories
    has_many :categories, through: :article_article_categories

    validates :title, presence: true, length: { minimum: 3, maximum: 50 }
    validates :description, presence: true, length: { minimum: 10, maximum: 500 }
    validates :author_id, presence: true

    attr_accessor :country
end

select 有效,用户可以 select 国家..完美!

但是它不会出现在我的view/show.html.erb..我试过这样:

<%= @article.country %>

因此我生成了一个迁移:

class AddCountryToArticles < ActiveRecord::Migration[5.0]
  def change
    add_column :article, :country, :string
  end
end

和运行迁移。

在我的控制器中,我将其添加到我的参数中:

def article_params
  params.require(:article).permit(:country, :title, :description, article_article_categories_ids: [])
end

但我一无所获.. 在 country_select 文档中,根据用法: “简单使用提供模型和属性作为参数: country_select("user", "country")"

但是我真的不知道,把那行代码放在哪里.. 我试图将它放入我的创建、显示和参数中。并更新为 ("article", "country")

有人可以帮我更近一步吗? 我也设计安装..也许这会引起一些麻烦? 我正在使用 rails 5.0.0

首先,删除attr_accessor :country,因为attr_accessor用于定义不与数据库中任何列映射的模型对象的属性。

回答你的问题“但我真的不知道该把那行代码放在哪里..我试着把它放在我的创建、显示和参数中..

您必须将那行代码放在窗体视图中。第一个属性是模型的名称(在你的例子中是文章),第二个是你的属性的名称(在你的例子中是国家)。但是,您已经正确地完成了此操作:

<%= f.country_select :country %>

您必须确保此表单确实适用于 Article,因此它应该是:

<%= form_for @article do |f| %>
  <div>
  <%= f.country_select :country %>
  </div>
<% end %>