0

i can't seem to be able to get the selected country to save to database. I've included a string column country_code in the model database.

i'm rending a partial here:

<%= f.label :country_code, "Country Traveled:" %>
<%= f.country_select :country_code, prompt: "Select a country" %>

In my controller:

    def new
        @user = User.new
    end

def index
    @user = User.all
  end

def create
    @user = User.new(user_params)

    if @user.save
      redirect_to @user
    else
      render 'new'
    end
  end

  def show
    @user = User.find(params[:id])
  end

  def edit
    @user = User.find(params[:id])
  end

private
    def user_params
      params.require(:user).permit(:country_code, :summary, :title, :text, :start_date, :end_date)
    end

In my model.rb:

class User < ActiveRecord::Base

    has_many :comments, dependent: :destroy

    attr_accessor :country_code

    validates :country_code, presence: true

    validates :summary, presence: true,length: { minimum: 5, maximum: 100 }

    validates :title, presence: true,
                      length: { minimum: 3 }

    validates :text, presence: true,
                      length: { minimum: 5 } 

    validates :start_date, presence: true

    validate :end_date_is_after_start_date

private
  def end_date_is_after_start_date
    return if end_date.blank? || start_date.blank?

      if end_date < start_date
        errors.add(:end_date, "End Date cannot be before the Start Date") 
      end 
  end

end

The drop-down in the view works fine, but when I hit submit, it doesn't save to database. Am I missing something? Thanks in advance!

gitastic
  • 516
  • 7
  • 26

1 Answers1

0

Share your entire controller and model please.

Normally, you can delete:

attr_accessor :country_code

It's useless because you save the country_code in your database and attr_accessor is just for virtual attribute, you can read more about that here: https://stackoverflow.com/a/20535041/3739191

PS: Your form for signup is build from scratch or not ?

Community
  • 1
  • 1
Sébastien P.
  • 526
  • 3
  • 14
  • Hi Spuyet - thanks for the reply. I've updated my original question with the full controller and model. Really hoping you can help. Thanks for your help! – gitastic Sep 25 '14 at 02:58
  • Thanks, I need more informations. The user is saved or not ? If yes, country_code is the only field that is not saved ? – Sébastien P. Sep 25 '14 at 07:57
  • Yes - all the other fields save (i.e., summary, title, date, etc.) - just the country_code does not save into database for some strange reason. =/ – gitastic Sep 25 '14 at 13:07
  • Thanks everyone! Seems like the attr_accessor line made the :country_code virtual, hence, not saving in the DB. Cheers! – gitastic Sep 26 '14 at 01:44