繁体   English   中英

Rails-如何为已插入表格创建视图

[英]Rails- How can I create view for nasted tables

我想在show.html.erb中获取这样的数据,但是它不起作用。 如何从竞价表中获取数据?

这是代码。

show.html.erb

<% @planaction.each do |action| %>

        <hr>
        <%= action.spot.name %>
        <%= action.spot.description %>
        <hr>

        <%= action.title %>
        <%= action.experience %>

<% end %>

plan.rb

class Plan < ActiveRecord::Base

  has_many :plan_actions

end

plan_action.rb

class PlanAction < ActiveRecord::Base
  belongs_to :plan
  has_one :spot
end

spot.rb

class Spot < ActiveRecord::Base
  belongs_to :plan_action
end

plan_actions_controller.erb

class PlanPagesController < ApplicationController
  def show
    @plan = Plan.find(params[:id])
    @planaction = @plan.plan_actions
  end
end

和错误消息在这里

nil:NilClass的未定义方法“名称”

这是竞价表的迁移文件。

    class CreateSpots < ActiveRecord::Migration
  def change
    create_table :spots do |t|
      t.integer :spot_id
      t.integer :plan_action_id
      t.string :name
      t.text :description
      t.time :time_open
      t.time :time_close
      t.date :dayoff
      t.string :address
      t.integer :tel
      t.string :image
      t.string :image2
      t.string :image3

      t.timestamps null: false
    end
  end
end

对我来说看上去很好。

问题可能是 (不确定是否没有看到您的日志) plan_action没有关联的spot记录。

要解决此问题,您应该使用一些条件逻辑:

<% @planaction.each do |action| %>
    <hr>
    <% if action.spot %>
       <%= action.spot.name %>
       <%= action.spot.description %>
       <hr>
    <% end %>

       <%= action.title %>
       <%= action.experience %>
<% end %>

再次,这是猜测。 我写了答案,因为我觉得最好提供某种解决方法的想法。 以上应该可以。

我还认为,作为Rich Peck,您在Spots表中没有记录,且plan_action_id与计划操作相对应。

遵循Rails约定,我建议以下几点:

class PlanAction < ActiveRecord::Base
  belongs_to :plan
  has_one :spot

  delegate :name, :description, to: :spot, prefix: true, allow_nil: true
end

并且在您看来:

<%= action.spot_name %>
<%= action.spot_description %>

最后,更正您的验证。 例如,如果一个plan_action应该有一个竞价点,那么您需要对竞价和计划动作都使用嵌套形式。

暂无
暂无

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

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