获取关联模型时的奇怪数据

时间:2014-03-13 19:14:22

标签: ruby-on-rails ruby activerecord

在我的应用程序中,我有两个模型之间的1:n关系。

class BuildsController < ApplicationController
  def create
    @user_application = UserApplication.find(params[:user_application_id])
    @build = @user_application.builds.create(params[:build].permit(:version, :description))
    redirect_to user_application_path(@user_application)
  end
end


class UserApplicationsController < ApplicationController

  def index
    @user_applications = UserApplication.all
  end

  def new
    @user_application = UserApplication.new
  end

  def create
    @user_application = UserApplication.new(user_application_params)
    if @user_application.save
      redirect_to @user_application
    else
      render 'new'
    end
  end

  def show
    @user_application = UserApplication.find(params[:id])
  end

  def edit
    @user_application = UserApplication.find(params[:id])
  end

  def update
    @user_application = UserApplication.find(params[:id])

    if @user_application.update(params[:user_application].permit(:name))
      redirect_to @user_application
    else
      render 'edit'
    end
  end

  def destroy
    @user_application = UserApplication.find(params[:id])
    @user_application.destroy

    redirect_to user_applications_path
  end

  private
  def user_application_params
    params.require(:user_application).permit(:name)
  end
end

<p>
  <strong>Name: </strong>
  <%= @user_application.name %>
</p>

<h2>Add a build</h2>

<%= form_for([@user_application, @user_application.builds.build]) do |f| %>
    <p>
      <%= f.label :version %>
      <%= f.text_field :version %>
    </p>
    <p>
      <%= f.label :description %>
      <%= f.text_field :description %>
    </p>
    <p>
      <%= f.submit %>
    </p>
<% end %>

<h2>Builds</h2>
<%= @user_application.builds.each do |build| %>
    <p>
      <strong>Version:</strong>
      <%= build.version%>
    </p>

    <p>
      <strong>Description:</strong>
      <%= build.description %>
    </p>
<% end %>

结构与Blog app非常相似。但是在我上面发布的展示页面上,我看到了一个奇怪的数据呈现。它看起来像这样:

Version:

Description:

[#<Build id: 1, description: "Initial", version: "1.0", user_application_id: 2, created_at: "2014-03-13 18:52:47", updated_at: "2014-03-13 18:52:47">, #<Build id: nil, description: nil, version: nil, user_application_id: 2, created_at: nil, updated_at: nil>]
那是什么?

UPD

现在我的问题是,虽然DB中没有依赖对象的记录,但Build模板的模板至少呈现一次。

如果我记录@ user_application.builds.emtpy的值?它产生&#34;假&#34;。

2 个答案:

答案 0 :(得分:2)

这是<%=上的= each。使用这种方式,您将输出构建数组 要仅输出块内的内容,请使用<% @user_application.builds.each do |build| %>

答案 1 :(得分:0)

更改<%= @user_application.builds.each do |build| %>

<% @user_application.builds.each do |build| %>

你看到的奇怪数据就是红宝石如何打印出一系列哈希