user984621
user984621

Reputation: 48453

Rails - how to display value through associations in form_for?

This is my view:

= form_for(@user) do |f|
  = f.autocomplete_field @user.city.name, autocomplete_city_name_users_path

On the second line I am trying to display the association, but I am getting

undefined method `London' for #<User:0x00000129bb3030>

The associations:

User belongs_to :city

City has_one :user

The displayed result in the error message (London) is right, but why I am gettng that error message?

Upvotes: 0

Views: 746

Answers (1)

Rob Davis
Rob Davis

Reputation: 15772

The argument to f.autocomplete_field should be the name of a method. The form builder will send this method to @user to get the correct value. Since the value you're interested in is not in user but in an object owned by user, you have a few options:

  1. Add city_name and city_name= methods to your User class:

    # app/models/user.rb
    
    def city_name
      city && city.name
    end
    
    def city_name=(name)
      city.name = name   # You'll want to make sure the user has a city first
    end
    

    If you don't know how to make sure you have a city, you could create one lazily by changing your city_name= method to this:

    def city_name=(name)
      build_city unless city
      city.name = name
    end
    

    Then your form would look like this:

    = form_for(@user) do |f|
      = f.autocomplete_field :city_name, autocomplete_city_name_users_path
    
  2. Or you could treat this as a nested object. Add this to User:

    accepts_nested_attributes_for :city
    

    And use fields_for in your form:

    = form_for(@user) do |f|
      = f.fields_for :city do |city_f|
        = city_f.autocomplete_field :name, autocomplete_city_name_users_path
    

Upvotes: 2

Related Questions