当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - Simple Form - setting an association collection to a default id

问题描述:

i am unsure how to go about resolving the below. Any help will be much appreciated

  • i have a user whoes profile states they comes from a country with an country_category_id: 8
  • when the user is completing an application form i would like to set the country select option by default to the country the user comes from (country_category_id: 8) as stated in the user's profile
  • in the _form.html.erb i have managed to this with firstname by adding "value: current_user.firstname"

question: could one advise how this would be done for s simpleform

association select option - setting the country select option to a default id based on the user country id

many thanks

schema

 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

model

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

网友答案:

I haven't worked with rails in a while but I'm trying to help.

Have you tried inserting :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   %>
分享给朋友:
您可能感兴趣的文章:
随机阅读: