简体   繁体   中英

Rails 3 - How to represent User model which belongs_to a City?

I have a User model and each users will have a company name and a cities associated with it. For the project, I need to list each users based on a city. eg: citywise/san-francisco, citywise/new-york. Currently these are the models in mind

class User < ActiveRecord::Base
  attr_accessible :name, :company

  belongs_to :city
end

class City < ActiveRecord::Base
  attr_accessible :name, :slug

  has_many :users
end

Also, the cities cannot be a predefined list. It should be created as each users are created in the DB.

So, how can I access or create the cities while the user is created/updated?

First things first, you need to add accepts_nested_attributes_for and attributes_for :cities_attributes to your City model:

class City < ActiveRecord::Base
  attr_accessible :name, :slug, attributes_for :cities_attributes
  accepts_nested_attributes_for :cities

  has_many_users
end

Since you now have access to all the attributes within your City model, you can include these in your form using fields for.

<%= form_for@city do |f| %>
   # City attributes
  <%= f.fields_for :users do |c| %>
     # User attributes
  <% end %>
<% end %>

In your index view you could also use nesting:

<% @cities.each do |city| %>
  # city attributes goes here
  <% city.users.each do |user| %>
    # user attributes goes here 

The first line shows all the attributes for each city you have defined, whereas the second line shows the attributes for each user for a particular city.

You'll need to look at nested attributes on your User model.

Here's the documentation for accepts_nested_attributes_for , a method which should help you out. http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM