簡體   English   中英

Rails關聯在控制台中有效,但在視圖中無效

[英]Rails association works in the console but not in the view

2個模型之間的多對多關聯。 它在控制台中完美運行,但是在視圖中,我得到的對象引用如下所示:

#<Author:0x0000000434bf80>
#<Author:0x000000043485b0>

這出現在我的視圖中,它具有以下代碼:

<h1 class="page-title">Articles</h1>
<hr>

<div class="category-container">
    <ul  class="category-titles">
      <% @cat.each do |c| %> 
       <li><%= link_to c.catName, category_path(c) %></li>
      <% end %>
  </ul>
</div>
<br><br><br><hr>

<% @art.each do |t| %>
 <p class="articles-list-page"><%= link_to t.artTitle, article_path(t)  %></p>
 <p><%= t.author %></p>
<% end %>

這是我在作者模型中的關聯

class Author < ActiveRecord::Base
 has_many :articles
end

這是我在文章模型中的關聯

 class Article < ActiveRecord::Base
    belongs_to :category
    belongs_to :author
 end

我不明白為什么它在控制台中運行良好,但在視圖中卻無法運行

它在視圖中工作正常。

這行:

<p><%= t.author %></p>

輸出作者模型。 您可能想要做的就是輸出作者姓名-類似

<p><%= t.author.name %></p>

您正在嘗試輸出與視圖的ActiveRecord關系。 您可能永遠不會希望在視圖中顯示整個ActiveRecord對象。 相反,您想顯示對象的特定屬性

如:

t.author.created_at
t.author.name
t.author.whatever

但是, 如果出於某些奇怪的原因想要將整個對象輸出到視圖,則可以像這樣使用inspect

t.author.inspect

更新:

要回答您遇到的另一個問題,您需要確保在嘗試將“作者”屬性輸出到視圖之前,確實對每個“ Articles 都有一個相關的“ Author ”。 您可以這樣完成:

<% if t.author.present? %>
  <p><%= t.author.authName %></p>
<% else %>
  <p>No author available</p>
<% end %>

或者像這樣,如果您想使用三元運算符將內容保持在一行上:

<p><%= t.author.present? ? t.author.authName : 'No author available' %></p>

或者,如果你不關心返回默認值,如“無可用的作者”如果一個author不可用,那么你可能只是做這樣的事情:

<p><%= t.author.try(:authName) %></p>

您應該將該作者屬性委托給Article模型

class Article < ActiveRecord::Base
  belongs_to :category
  belongs_to :author
  delegates :authName, allow_nil: true
end

同樣在您的控制器中使用以下代碼

class ArticleController < ApplicationController
  def index
    @art = Article.includes(:author).all
  end
end

在您看來像波紋管一樣使用

<% @art.each do |t| %>
 <p class="articles-list-page"><%= link_to t.artTitle, article_path(t)  %></p>
 <p><%= t.authName %></p>
<% end %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM