gpt4 book ai didi

ruby-on-rails - Rails has_many belongs_to with foreign_key 和 class_name

转载 作者:行者123 更新时间:2023-12-05 07:58:22 25 4
gpt4 key购买 nike

我正在尝试为 UserMessage 系统建模。 Messageaddresseraddressee用户sent_messagereceived_messages

目前测试失败,因为它似乎无法找到 addressee_id 和 addresser_id。我想知道我是否已正确建模,以及我应该如何通过用户创建消息。

编辑:测试的输出

ActiveRecord::UnknownAttributeError:未知属性:addressee_id

在消息规范中的 before 语句中弹出。

用户模型

class User < ActiveRecord::Base
has_many :sent_messages, class_name: "Message", foreign_key: "addresser_id"
has_many :received_messages, class_name: "Message", foreign_key: "addressee_id"

消息模型

class Message < ActiveRecord::Base
validates :addresser_id, presence: true
validates :addressee_id, presence: true
belongs_to :addresser, class_name: "User", foreign_key: "addresser_id"
belongs_to :addressee, class_name: "User", foreign_key: "addressee_id"
end

迁移

class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.string :content
t.integer :addresser_id
t.integer :addressee_id
t.timestamps
end
add_index :messages, [:addressee_id, :addresser_id, :created_at]
end
end

架构

create_table "messages", force: true do |t|
t.string "content"
t.integer "addresser"
t.integer "addressee"
t.datetime "created_at"
t.datetime "updated_at"
end

add_index "messages", ["addressee", "addresser", "created_at"], name: "index_messages_on_addressee_and_addresser_and_created_at"

消息规范

require 'spec_helper'

describe Message do
let(:user1) { FactoryGirl.create(:user) }
let(:user2) { FactoryGirl.create(:user) }
before { @message = user1.sent_messages.build(content: "Lorem ipsum", addressee_id: user2.id) }

subject { @message }

it { should respond_to(:content) }
it { should respond_to(:addresser_id) }
it { should respond_to(:addressee_id) }
its(:addresser) { should eq user1 }

it { should be_valid }

describe "when addresser is not present" do
before { @message.addresser = nil }
it { should_not be_valid }
end

describe "when addressee is not present" do
before { @message.addressee = nil }
it { should_not be_valid }
end
end

最佳答案

尝试替换这个:

describe Message do
...
before { @message = user1.sent_messages.build(content: "Lorem ipsum", addressee_id: user2.id) }
subject { @message }
...
end

有了这个:

describe Message do
...
let(:message){ user1.sent_messages.build(content: "Lorem ipsup", addressee_id: user2.id) }
subject { message }
...
end

还要检查迁移是否在测试环境中运行。

编辑:ActiveRecord::UnknownAttributeError 表示数据库中缺少一列。迁移似乎没问题,但 Message.column_names 的模式和输出却没有。

似乎您的 addressee_id/addresser_id 在数据库中实际上被命名为 addressee/addresser 。您是否在运行 db:migrate 后编辑了迁移文件?

尝试运行 rake db:migrate:redo STEP=1(如果这不是您最后一次迁移,请更改步骤)

关于ruby-on-rails - Rails has_many belongs_to with foreign_key 和 class_name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24896152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com