2张桌子之间的关联不起作用

时间:2019-05-24 13:00:00

标签: ruby-on-rails

我是RoR的新手,我想创建一个像任务管理器一样的简单页面(添加和删除任务),所以我创建了2个表,它们之间具有关联(Track和Item)。 这是2种型号:

class Item < ApplicationRecord
  belongs_to :track, optional: :true
end

class Track < ApplicationRecord
  has_many :items, dependent: :destroy
end

当我创建或删除任何跟踪项目时,我需要设置关联。但是当我创建它时,我只看到我的跟踪项(关联表中有一个空字段)

For example: 
rails c
Track.create(item: 'Asafa Pauel', description: 'This is a description') - works fine (added all field to db)
Item.all - track_id field is empty - but it should show id of track item. Why is this?

还有我的Tracks控制器:

class TracksController < ApplicationController
  def index
    @track = Track.all
  end

  def show
    @track = Track.all
  end

  def new
    @track = Track.new
  end

  def create
    @track = Track.new(track_params)
    @item = Item.new(track_id: @track.id)
    if @track.save! && @item.save!
      flash[:success] = "It works!"
      redirect_to tracks_path
    else
      flash[:success] = "Its wrong!"
    end
  end

private
  def track_params
    params.require(:track).permit(:item, :description)
  end
end

和项目控制器:

class ItemsController < ApplicationController
  def create
    @item = Item.new(item_params)
  end

  private
  def item_params
    params.require(:item).permit(:track_id)
  end
end

和数据库模式:

ActiveRecord::Schema.define(version: 2019_05_23_112947) do

  enable_extension "plpgsql"

  create_table "items", force: :cascade do |t|
    t.bigint "track_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["track_id"], name: "index_items_on_track_id"
  end

  create_table "tracks", force: :cascade do |t|
    t.string "item"
    t.string "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

预先感谢

1 个答案:

答案 0 :(得分:0)

您的新“ Track”对象还没有ID,因此您无法将其值分配给Item.track_id。

首先,您必须保存轨道,然后创建一个新项目。

此外,如果您从控制台创建新的Track,则不会在控制器中触发您的“ create”方法:仅当您从浏览器中创建新的Track时,该方法才会被调用。

如果您想在每次创建Track时都创建一个新Item,则必须在模型文件“ track.rb”中执行以下操作:

after_save :create_new_item

def create_new_item
    self.items.create
end

P.S。:“ track.rb”文件位于Rails应用程序的“ app / models”中。