[英]Rails: showing an attribute from an associated model
我正在嘗試使用Rails 4制作一個應用程序。
我有個人資料顯示頁面,其中應包含個人資料所屬大學的名稱。
我的個人資料中有此鏈接#show:
<%= link_to @profile.university.name do %>
<span class="profiletitle"> <%= @profile.university.name %></span>
<% end %>
我有個人資料模型和大學模型。 關聯是:
profile: belongs_to :university
university: has_many :profiles
在我的大學表中,我有一個名為:name的屬性。
嘗試此操作時,出現錯誤消息:
ActiveRecord::RecordNotFound at /profiles/University%20of%20Melbourne
Couldn't find Profile with 'id'=University of Melbourne
它指的是我的配置文件控制器,具有(在錯誤參考點所在的行):
def set_profile
@profile = Profile.find(params[:id])
end
我不明白為什么這種參考是相關的,或者如何從個人資料顯示中參考大學名稱。 我希望ti能夠正常工作,因此您單擊鏈接即可帶您到uni概述顯示頁面。
您如何從關聯模型中引用屬性?
我問了其他幾個問題,試圖解決此錯誤。 最近的一個在這里。 給出了廣泛的答案,但是我不希望像建議中那樣建立聯系,所以我迷失了如何遵循答案的內容。
http://stackoverflow.com/questions/32916133/rails-how-to-show-attribute-of-an-associated-model
謝謝
當我接受Prashant的建議並嘗試:
<%= link_to universities_path(@profile.university) do %>
<span class="profiletitle"> <%= @profile.university.name %></span>
<% end %>
我收到此錯誤:
ActionController::UnknownFormat
它在我的大學控制器中引用了此操作:
def index
@universities = University.all
respond_with(@university)
end
我的個人資料路線為:
resources :profiles do
resources :account_histories
end
您的用法是這樣的:
更新
<%= link_to university_path(@profile.university) do %>
<span class="profiletitle"> <%= @profile.university.name %></span>
<% end %>
您的routes.rb應該包含這個
resources :universities do
resources :profiles
# other stuff
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.