user2254488 user2254488 - 4 years ago 82
Ruby Question

Rails: Save country_select to database

I’m working on a form where user can pick country and there choice will be shown and show.html.erb.

I have added country_select in my form like this

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

My model article.rb looks like this:

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

The select works and the user can select country.. Perfect!

But it won’t show up in my view/show.html.erb.. I have tried like this:

<%= %>

So therefor I generated a migration:

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

And ran the migration.

In my controller I added this to my params:

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

But I get nothing..
At country_select documentation, under usage:
"Simple use supplying model and attribute as parameters:
country_select("user", "country")"

But I don’t really know, where to put that line of code..
I have tried to put it in my create, show, and params.. And updated with (“article”, "country")

Can someone help me to get a step closer?
I also devise installed.. Maybe that could cause some trouble?
I'm working with rails 5.0.0

Answer Source

First, get rid of attr_accessor :country as attr_accessor is used to define an attribute for object of Model which is not mapped with any column in database.

To answer your question "But I don’t really know, where to put that line of code.. I have tried to put it in my create, show, and params.. "

You have to put that line of code in your form view. The first attribute is the name of the model (article in your case) and the second is the name of your attribute (country in your case). You have already properly done this however with:

<%= f.country_select :country %>

You have to make sure that this form is actually for an Article so it should be:

<%= form_for @article do |f| %>
  <%= f.country_select :country %>
<% end %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download