Show selected name instead of ID in rails index view

So, I'm new to rails, and I try my best to follow the tutorials that abound in the network. So, I have three tables.

class CreateAuthors < ActiveRecord::Migration def self.up create_table :authors do |t| t.string :name t.string :email t.timestamps end end def self.down drop_table :authors end end class CreateTopics < ActiveRecord::Migration def self.up create_table :topics do |t| t.string :category t.timestamps end end def self.down drop_table :topics end end 

Now a link to articles author_id and topic_id

 class CreateArticles < ActiveRecord::Migration def self.up create_table :articles do |t| t.string :title t.integer :author_id t.integer :topic_id t.text :content t.integer :status t.timestamps end end def self.down drop_table :articles end end 

Now for new.html.erb and edit.html.erb, I learned how to use collection_select to get posts from topics and authors.

 <% form_for(@article) do |f| %> <%= f.error_messages %> <p> <%= f.label :title %><br /> <%= f.text_field :title %> </p> <p> <%= f.label :author_id %><br /> <%= @authors =Author.find(:all, :order => 'name') collection_select(:article,:author_id, @authors,:id,:name) %> </p> <p> <%= f.label :topic_id %><br /> <%= @topics = Topic.find(:all, :order => 'category') collection_select(:article,:topic_id, @topics,:id,:category) %> </p> <p> <%= f.label :content %><br /> <%= f.text_area :content %> </p> <p> <%= f.label :status %><br /> <%= f.text_field :status %> </p> <p> <%= f.submit 'Create' %> </p> <% end %> <%= link_to 'Back', articles_path %> 

Now for my view, how do I return names to the index and show the view, not id?

 <td><%=h article.topic_id %></td> <td><%=h article.title %></td> <td><%=h article.author_id %></td> <td><%=h article.status %></td> 

Any help would be greatly appreciated.

+4
source share
2 answers

It:

 @authors =Author.find(:all, :order => 'name') 

and this:

 @topics = Topic.find(:all, :order => 'category') 

must be in your controller in the appropriate actions ( new and edit ).

Your models should look like this:

 # Article model belongs_to :author belogns_to :topic # Author model has_many :articles # Topic model has_many :articles 

With this, you can do what you want in this way:

 <td><%=h @article.title %></td> <td><%=h @article.author.name %></td> <td><%=h @article.status %></td> 

And any other options: @article.topic.category , @author.articles.first.topic , etc.

+5
source

This approach is not entirely suitable for Ruby on Rails, you mix controller logic in your view. You should have @authors = Author.find(:all, :order => 'name') , etc. In your controller, not in your view.

Similarly, in your controller you will have:

 @author = Author.find(@article.author_id); 

And in your view you will see the name of the author:

 <%=h @author.name %> 
+3
source

Source: https://habr.com/ru/post/1302066/


All Articles