Answer the question
In order to leave comments, you need to log in
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
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
<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>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question