简体   繁体   English

Rails:显示关联模型中的属性

[英]Rails: showing an attribute from an associated model

I am trying to make an app with Rails 4. 我正在尝试使用Rails 4制作一个应用程序。

I have a profile show page which should include the name of the university that the profile belongs to. 我有个人资料显示页面,其中应包含个人资料所属大学的名称。

I have this link in my profiles#show: 我的个人资料中有此链接#show:

<%= link_to @profile.university.name do %>
            <span class="profiletitle"> <%= @profile.university.name %></span>
<% end %>

I have a profile model and a university model. 我有个人资料模型和大学模型。 The associations are: 关联是:

profile: belongs_to :university

university: has_many :profiles

In my universities table, I have an attribute called :name. 在我的大学表中,我有一个名为:name的属性。

When I try this, I get an error saying: 尝试此操作时,出现错误消息:

ActiveRecord::RecordNotFound at /profiles/University%20of%20Melbourne
Couldn't find Profile with 'id'=University of Melbourne

It refers to my profiles controller, which has (at the line where the error reference points): 它指的是我的配置文件控制器,具有(在错误参考点所在的行):

 def set_profile
      @profile = Profile.find(params[:id])
 end

I dont understand why this reference is relevant or how to reference the university name from the profile show. 我不明白为什么这种参考是相关的,或者如何从个人资料显示中参考大学名称。 I want ti to works so you click the link and it takes you to the uni overview show page. 我希望ti能够正常工作,因此您单击链接即可带您到uni概述显示页面。

How do you reference an attribute from an associated model? 您如何从关联模型中引用属性?

I have asked several other questions trying to fix this error. 我问了其他几个问题,试图解决此错误。 The most recent one is here. 最近的一个在这里。 There is an extensive answer given, but I don't want the associations set out like the suggestion provides for so I"m getting lost on how to follow along with the content of the answer. 给出了广泛的答案,但是我不希望像建议中那样建立联系,所以我迷失了如何遵循答案的内容。

http://stackoverflow.com/questions/32916133/rails-how-to-show-attribute-of-an-associated-model

Thank you 谢谢

When I take Prashant's suggestion and try: 当我接受Prashant的建议并尝试:

<%= link_to universities_path(@profile.university) do %>
   <span class="profiletitle"> <%= @profile.university.name %></span>
 <% end %>

I get this error: 我收到此错误:

ActionController::UnknownFormat

It references this action in my universities controller: 它在我的大学控制器中引用了此操作:

def index
    @universities = University.all
    respond_with(@university)
  end

My profile routes are: 我的个人资料路线为:

resources :profiles do
    resources :account_histories
  end

yourUse like this: 您的用法是这样的:

UPDATE 更新

 <%= link_to university_path(@profile.university) do %>
   <span class="profiletitle"> <%= @profile.university.name %></span>
 <% end %>

Your routes.rb should contain this 您的routes.rb应该包含这个

resources :universities do
  resources :profiles
  # other stuff
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM