0

I have 2 associated models (items and cities - cities is already populated by me) and a form where users can enter things they notice in a city. They can now enter the name of that thing and the ID of the city. However, obviously I would like to let them enter the NAME of the city and get the id of that name, given that his city exists in my database.

What can I do to achieve that and get the id?

Here are my models:

class City < ActiveRecord::Base
  has_many :items
end

class Item < ActiveRecord::Base
  belongs_to :city
end

and the reference in schema.rb

add_index "items", ["city_id"], name: "index_items_on_city_id", using: :btree

Form:

<%= form_for :item, url: items_path do |f| %>
  <%= f.text_field :name %> 
  <%= f.text_field :city_id %>
<% end %>

Items controller:

def create
    @item = Item.new(params[:item].permit(:name, :city_id))
end

Thanks a lot!

watt
  • 799
  • 3
  • 8
  • 22

2 Answers2

0

You have correctly setup the associations but you need to create a new item which is associated with city so i think it will be best if you remove text field for city in your form and you need to write City.items.create(params) in your controller. This will take care of your association

Mandeep
  • 9,093
  • 2
  • 26
  • 36
  • Thanks for replying but I don't understand, sorry. So I should remove `<%= f.text_field :city_id %>` from the view and add `City.items.create(params)` in my controller? This doesn't work. – watt Oct 18 '13 at 06:51
  • yeah unless you want to use a drop down list or something from which the user's can select city..can you paste your controller's code. i want to see the changes that you did – Mandeep Oct 18 '13 at 06:54
  • 1
    You need to first find the city by @city= City.find(id) and then do @city.items.create(params). If you don't have any condition by which you can find city then you just have to use a drop down list, there's no alternative – Mandeep Oct 18 '13 at 07:02
0

Fixed this using @Nikita Singhs' advice regarding the dropdown and now it works. This is how my form looks:

<%= form_for :item, url: items_path do |f| %>
  <%= f.text_field :name %> 
  <%= f.collection_select :city_id, City.order(:name),:id, :name, include_blank: true %>
<% end %>

Thanks for taking the time to respond!

watt
  • 799
  • 3
  • 8
  • 22