简单表单 - 将关联集合设置为默认标识

时间:2016-02-01 14:53:10

标签: ruby-on-rails ruby-on-rails-4

我不确定如何解决以下问题。任何帮助将不胜感激

  • 我有一个用户个人资料说明他们来自的国家/地区是country_category_id:8
  • 当用户填写申请表时,我想将国家/地区选择选项默认设置为用户来自的国家/地区(country_category_id:8),如用户个人资料中所述
  • 在_form.html.erb中,我通过添加"值:current_user.firstname"
  • 来设置为firstname
  

问题:可以建议如何对简单形式进行此操作   关联选择选项 - 根据用户国家/地区ID

将国家/地区选择选项设置为默认ID
非常感谢

模式

  create_table "users", force: true do |t|
    t.string   "firstname"
    t.string   "lastname"
    t.integer  "number"
    t.string   "email"
    t.text     "language"
    t.integer  "category_country_id"
  end


  create_table "forms", force: true do |t|
    t.string   "firstname"
    t.string   "lastname"
    t.integer  "number"
    t.string   "email"
    t.integer  "category_country_id"
  end

  create_table "category_countries", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

模型

User belongs_to category_country
Form belongs_to category_country

CategoryCountry has_many users
CategoryCountry has_many forms

views:forms / _form.html.erb

<%= f.input_field :firstname, value: current_user.firstname %>
<%= f.association :category_country, collection: CategoryCountry.all, prompt: "select a category", label: "current country (you currently live in)", :value => current_user.category_country.name %>

forms_controller.rb

  def new
    @user = current_user
    @form = Form.new
  end

  def create
    @form = Form.new(form_params)
    @form.user_id = current_user.id
    if @form.save
      redirect_to application_submitted_path
    else
      redirect_to user_advert_path(advert.user, advert)
    end
  end

1 个答案:

答案 0 :(得分:1)

我暂时没有使用过rails,但我正在努力提供帮助。

您是否尝试过插入:selected => current_user.category_country_id

<%= f.association :category_country, collection: CategoryCountry.all, prompt: "select a category", label: "current country (you currently live in)", :value => current_user.category_country.name, :selected => current_user.category_country_id   %>