简体   繁体   English

Rails索引方法显示带有子记录的父级

[英]Rails index method display parent with child records

know this is a bone-headed question, but I cant find what im looking for. 知道这是一个脑筋急转弯的问题,但是我找不到我想要的东西。

I have two models: parent and child 我有两个模型:父母和孩子

class child < ActiveRecord::Base
  belongs_to :parent
end

class parent < ActiveRecord::Base
  has_many :childs
end

in the child controller index action I would like to display a field from the parent model with each of the queried records. 在子控制器索引操作中,我想显示父模型的字段以及每个查询的记录。

def index
  @childs = Childs.all
end

How do I display the parent_name in the view with the child records? 如何在带有子记录的视图中显示parent_name?

for example: 例如:

<%= @childs.each do |c| %>
  <%= child.name %>
  <%= child.parent.name %>
<% end %>

Here is a list of issues that I found with your code. 这是我在您的代码中发现的问题列表。

  • Your model names should be capitalized. 您的型号名称应大写。
  • When setting the association, your childs should be children . 设置关联时,您的childs应该是children
  • When setting @childs , your should reference the model as Child , not Childs 设置@childs ,应将模型引用为Child ,而不是Childs
  • You're looping through each record of the children with c but you reference them as child 您正在使用c遍历子项的每条记录,但您将它们称为child
  • There is no need for <%= in the first line. 第一行不需要<%=

Correcting these should look like this and it should work. 纠正这些问题看起来应该是这样,并且应该可以进行。 If you are having other issues, post the error message and relevant code. 如果您还有其他问题,请发布错误消息和相关代码。

Models 楷模

class Child < ActiveRecord::Base
  belongs_to :parent
end

class Parent < ActiveRecord::Base
  has_many :children
end

Controller 调节器

def index
  @childs = Child.all
end

View 视图

<% @childs.each do |child| %>
  <%= child.name %>
  <%= child.parent.name %>
<% end %>

If you're having a nil class, maybe it's because your :parent_id doesn't carry your parent's id when creating the record. 如果您使用的是nil类,则可能是因为:parent_id在创建记录时没有携带父母的ID。

You may go to rails console and enter 'Child.all' to see if all your :parent_ids are nil or not. 您可以转到Rails控制台并输入'Child.all',以查看您所有的:parent_ids是否均为nil。

I myself have a user model that has_many :tweets,and each tweet model belongs_to :user. 我本人有一个具有has_many:tweets的用户模型,并且每个tweet模型都属于_user:user。 In my tweet.controller.rb, I set up the def create as follows to enter user's id into :user_id column: 在我的tweet.controller.rb中,我按如下所示设置def create,以便在:user_id列中输入用户ID:

def create
    @tweet = current_user.tweets.new(tweet_params)
    if @tweet.save
      flash[:notice] = "You've updated with a tweet."
      redirect_to admin_tweets_path
    else
      @tweets = Tweet.all
      render :index
    end
  end

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

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