0

ライブラリを実装していますが、カテゴリの表があります。

カテゴリ表は次のとおりです。-

 id serial NOT NULL,
  name character varying(255),
  parent_cat_id integer DEFAULT 0,
  deleted integer NOT NULL DEFAULT 0,
  CONSTRAINT categories_pkey PRIMARY KEY (id)

今私が直面している問題は、参照しているカテゴリのIDではなく、カテゴリの名前を表示したいということです。

私のindex.html.erbファイルは次のとおりです:-

<table class="table table-striped table-bordered">
  <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Parent Category Id</th>
    <th>Edit</th>
    <th>Delete</th>
  </tr>

<% @categories.each do |c| %>
  <tr>
    <td><%= c.id %>&nbsp;</td>
    <td><%= c.name %>&nbsp;</td>
    <td><%= c.parent_cat_id %>&nbsp;</td>
    <td><%= link_to 'Edit', {:action => 'edit', :id => c.id} %> &nbsp;</td>
    <td><%= link_to 'Delete', {:action => 'delete', :id => c.id},
    :data => { :confirm => "Are you sure you want to delete this value?" } %></td>
    </tr>
  </tr>
<% end %>
</table>

<br />

これを実装する方法はありますか?

4

2 に答える 2

2

カテゴリモデルに以下を追加できます

class Category < ActiveRecord::Base
  belongs_to :parent_category, class_name: 'Category', foreign_key: :parent_cat_id
end

次に、次のことを行うことができます

<td><%= c.parent_category.name if c.parent_category %>&nbsp;</td>

ifカテゴリに親カテゴリがない場合にエラーが発生しないことを確認するために追加しました

于 2013-03-14T11:33:34.993 に答える
-1

これを試して、

<td><%= c.parent_cat_id.name %>&nbsp;</td>

モデルが関連している場合に機能します。

于 2013-03-14T11:16:02.040 に答える