一对多关系搜索无效id



我正在做一个学校项目,我是ROR的新手。我有两件物品,收据和主题。收据有一个主题,主题在收据中重复使用。如果我有相同数量的收据主题,我没有问题,但当我没有为收据创建新主题时,我会收到以下错误:错误的屏幕截图
这里的问题是,我在数据库中只有两个主题和3张收据。所以主题的id为3是无效的。下面是我的模型、视图、控制器和迁移。

class Receipt < ActiveRecord::Base 
belongs_to :user
has_one :subject, :foreign_key => :id
validates :user_id, presence:true
validates :descript, presence: true, length: { minimum: 4, maximum: 120      }
end
class Subject < ActiveRecord::Base
has_many :receipts
validates :subject_name, presence: true, length: { minimum: 2, maximum: 30 }
validates :description, presence: true, length: { minimum: 2, maximum: 200 }
end

The View: 
<% @receipts.each do |receipt| %>
    <tbody>
        <tr>
            <td><%= receipt.date %></td>
            <td><%= receipt.subject.subject_name %></td>
        </tr>
    </tbody>
    <% end %>
 class ReceiptsController < ApplicationController 
    def index
    @receipts = Receipt.paginate(page: params[:page], per_page: 4).order("updated_at DESC")
    end
    end

class CreateReceipts < ActiveRecord::Migration
def change
create_table :receipts do |t|
  t.datetime :date
  t.decimal :tax_amount, :purchase_amount, precision: 5, scale: 2
  t.boolean :approved, default: false
  t.text :descript
  t.integer :user_id, :subject_id
  t.timestamps
end
end
end

class CreateSubjects < ActiveRecord::Migration
def change
create_table :subjects do |t|
t.string :subject_name
t.text :description
t.timestamps
end
end
end

我认为我的迁移和观点很好,因为当我对收据有平等的主体时,它是有效的,但我真的很感激在这一点上的任何反馈。提前谢谢!

问题在于您的关联。has_one关联试图查找关联表,在这种情况下为Subject,具有foreign_key的记录等于具有关联Receipt的对象的id,在这种情形下为3。

你可以去掉has_one :subject,转而使用这样的方法

def subject
  Subject.find_by_id subject_id
end

或者,您可以将关联更改为belongs_to :subject

您不应该在关联的两边都有has_onehas_many。由于Subject中有has_many,因此应在Receipt中使用belongs_to

希望能有所帮助。

最新更新