Create user field with options

Hi I am playing around with the imports scripts and I want to create a drop down user field. The ning script has an example of creating a text field which I have working, and I am able to add a dropdown w/ no options, but when I change the type to drop down and add an options attribute like so

     @interests_field = UserField.find_by_name("My interests5")
     unless @interests_field
       @interests_field = UserField.create(name: "My interests5", description: "Do you like stuff5?", field_type: "dropdown", editable: true, required: true, show_on_profile: true, show_on_user_card: true, options: ['a','b', 'c'] )
     end

I get this error:

.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.6/lib/active_record/attribute_assignment.rb:59:in `rescue in _assign_attribute’: unknown attribute ‘options’ for UserField. (ActiveRecord::UnknownAttributeError)

I am new to ruby and discourse but I think the relevant code is in

./app/controllers/admin/user_fields_controller.rb

There is also a file

./spec/controllers/admin/user_fields_controller_spec.rb

which suggests that options should be passable somehow?

Thanks to anyone who can shed light on this mystery.

Specifically how can I add options programmatically when creating a userfield in a ruby script situation.

1 Like

Woohoo, I figured out a way thanks to a random code snippets found on the web.

In local development, run like so:

~/discourse> rails runner script/import_scripts/test.rb

test.rb

require "mysql2"

require File.expand_path(File.dirname(__FILE__) + "/base.rb")



class ImportScripts::UserFieldCreator < ImportScripts::Base

  def initialize
    super
  end


  def execute
     @interests_field = UserField.find_by_name("My interests5")
     unless @interests_field
       @interests_field = UserField.create(name: "My interests5", description: "Do you like stuff5?", field_type: "text", editable: true, required: true, show_on_profile: true, show_on_user_card: true)
     end

     @interests_field = UserField.find_by_name("My interests7")
     unless @interests_field
       @interests_field = UserField.create(name: "My interests7", description: "Do you like stuff6?", field_type: "dropdown", editable: true, required: true, show_on_profile: true, show_on_user_card: true)
        UserFieldOption.create(user_field_id: @interests_field.id, value: 'not really')
        UserFieldOption.create(user_field_id: @interests_field.id, value: 'a bit')
        UserFieldOption.create(user_field_id: @interests_field.id, value: 'some')
        UserFieldOption.create(user_field_id: @interests_field.id, value: 'a lot')
     end
  end
end

if __FILE__==$0
  ImportScripts::UserFieldCreator.new.perform
end
2 Likes