加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:50:46 所属栏目:百科 来源:网络整理
导读:所以我是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
所以我是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

现在文章引用了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

现在对于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,: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 %>

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

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

任何帮助将不胜感激.

解决方法

这个:

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

还有这个:

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

应该在你的控制器中进行相应的操作(新建和编辑).

您的模型应如下所示:

# Article model
belongs_to :author
belogns_to :topic

# Author model
has_many :articles

# Topic model
has_many :articles

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

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

以及任何其他变体:@ article.topic.category,@ author.articles.first.topic等.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读