【问题标题】:Rails index method display parent with child recordsRails 索引方法显示父子记录
【发布时间】:2014-04-18 20:14:13
【问题描述】:

知道这是一个愚蠢的问题,但我找不到我要找的东西。

我有两个模型:父母和孩子

class child < ActiveRecord::Base
  belongs_to :parent
end

class parent < ActiveRecord::Base
  has_many :childs
end

在子控制器索引操作中,我想显示来自父模型的字段以及每个查询的记录。

def index
  @childs = Childs.all
end

如何在包含子记录的视图中显示 parent_name?

例如:

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

【问题讨论】:

  • 对于那些将来阅读本文的人来说,使用children(child 的复数形式)而不是childs 可能是个好主意。我的两分钱。

标签: ruby-on-rails


【解决方案1】:

这是我在您的代码中发现的问题列表。

  • 您的型号名称应大写。
  • 设置关联时,您的childs 应为children
  • 在设置@childs 时,您应该将模型引用为Child,而不是Childs
  • 您使用c 循环遍历子项的每条记录,但您将它们引用为child
  • 第一行不需要&lt;%=

纠正这些应该看起来像这样,它应该可以工作。如果您有其他问题,请发布错误消息和相关代码。

模型

class Child < ActiveRecord::Base
  belongs_to :parent
end

class Parent < ActiveRecord::Base
  has_many :children
end

控制器

def index
  @childs = Child.all
end

查看

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

【讨论】:

  • 我已将您的答案标记为正确,因为您指出了正确的方法。经过大量的试验和错误,很明显我的问题是我使用带有 rails 4 的 Devise(父模型)并且没有 attr-accesable(或 rails 4 equiv。)我得到一个 nil 类错误。如果您有任何解决此问题的想法,请告诉我。
  • @kobaltz 谢谢你的回答。我不会child.parent.name 每次都访问数据库吗?如果是这样,有没有办法将这种影响降到最低?
【解决方案2】:

如果你有一个 nil 类,可能是因为你的 :parent_id 在创建记录时没有携带你父母的 id。

你可以去 rails 控制台并输入 'Child.all' 来查看你所有的 :parent_ids 是否都是 nil。

我自己有一个用户模型 has_many :tweets,每个推文模型都属于_to :user。在我的 tweet.controller.rb 中,我将 def create 设置如下,将用户的 id 输入到 :user_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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    相关资源
    最近更新 更多