简体   繁体   English

rails,国家gem-不保存到数据库

[英]rails, countries gem - not saving to database

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. 我在模型数据库中包含了一个字符串列country_code。

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: 在我的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! 提前致谢!

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 这没有用,因为您将country_code保存在数据库中,并且attr_accessor仅用于虚拟属性,您可以在此处阅读有关此内容的更多信息: https ://stackoverflow.com/a/20535041/3739191

PS: Your form for signup is build from scratch or not ? PS:您的注册表单是从头开始的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM