在rails索引视图中显示所选名称而不是ID

DT.*_*DT. 4 ruby ruby-on-rails

所以我是rails的新手,我正在努力,因为我可以按照大量的网络教程.所以我有三张桌子.

  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
Run Code Online (Sandbox Code Playgroud)

现在文章引用了author_id和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
Run Code Online (Sandbox Code Playgroud)

现在对于new.html.erb和edit.html.erb,我发现了如何使用collection_select来获取主题和作者的记录.

<% 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 %>
Run Code Online (Sandbox Code Playgroud)

现在我的视图如何返回索引和显示视图中的名称而不是id?

<td><%=h article.topic_id %></td>
    <td><%=h article.title %></td>
    <td><%=h article.author_id %></td>
    <td><%=h article.status %></td>
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

kle*_*lew 5

这个:

@authors =Author.find(:all, :order => 'name')
Run Code Online (Sandbox Code Playgroud)

还有这个:

@topics = Topic.find(:all, :order => 'category') 
Run Code Online (Sandbox Code Playgroud)

应该在你的控制器中进行相应的动作(newedit).

您的模型应如下所示:

# Article model
belongs_to :author
belogns_to :topic

# Author model
has_many :articles

# Topic model
has_many :articles
Run Code Online (Sandbox Code Playgroud)

有了这个,你可以用这种方式做你想做的事:

<td><%=h @article.title %></td>
<td><%=h @article.author.name %></td>
<td><%=h @article.status %></td>
Run Code Online (Sandbox Code Playgroud)

和任何其他的变化:@article.topic.category,@author.articles.first.topic等等.