D
D
dexdev2013-12-26 22:58:59
Ruby on Rails
dexdev, 2013-12-26 22:58:59

How to add cities (location) for users correctly?

The question is super noob, how to make cities for users correctly, an example when registering a user indicates a city, after which all his actions point to the city specified during registration, let's say he posts different blog posts, and on the page with all posts it is indicated that these mails belong to a certain city, is it really as simple as two and two, that is, create a City label and write it in the models cities has_many users, users belongs_to city and that's it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
eliastro, 2014-01-06
@AdilA

We create 3 models and link them:

class City < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  has_many :posts
  belongs_to :city
end

class Post < ActiveRecord::Base
  belongs_to :user
end

Further, for example, when displaying all posts (the index action of the PostsController controller), we also needed to display the city of the post author. Then in the post index.html.erb view, the output of the city is post.user.city.name. Implementation example:
<table>
  <thead>
    <tr>
      <th>User</th>
      <th>City</th>
      <th>Text</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>

  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= link_to post.user.name, user_path(post.user) %></td>
        <td><%= post.user.city.name %></td>
        <td><%= post.text %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

I'm learning Rails myself. It may be possible to do everything more elegantly. But checked - works.

S
Snuff, 2014-01-04
@Snuff

Young man, please read books, guides, watch video tutorials. After that, I hope you will not have such questions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question