我遇到了多对多关系的问题。我通过名为rtimespans的第三方建立了这种关系。
就像在教程中说的那样:
时间跨度模型:
class Timespan < ActiveRecord::Base
validates :name, presence: true
has_many :rtimespans
has_many :subgroups, through: :rtimespans
validates :start_h, presence: true
validates :start_m, presence: true
validates :end_h, presence: true
validates :end_m, presence: true
validate :e_must_be_0_60
validate :e_must_be_0_24
validate :s_must_be_0_60
validate :s_must_be_0_24
validate :e_bigger_s
def e_must_be_0_60
errors.add(:end_m,"must be 0-60") unless 0 < end_m.to_i
errors.add(:end_m,"must be 0-60") unless 60 > end_m.to_i
end
def e_must_be_0_24
errors.add(:end_h,"must be 0-24") unless 0 < end_h.to_i
errors.add(:end_h,"must be 0-24") unless 24 > end_h.to_i
end
def s_must_be_0_60
errors.add(:start_m,"must be 0-60") unless 0 < start_m.to_i
errors.add(:start_m,"must be 0-60") unless start_m.to_i < 60
end
def s_must_be_0_24
errors.add(:start_h,"must be 0-24") unless 0 < start_h.to_i
errors.add(:start_h,"must be 0-24") unless start_h.to_i < 24
end
def e_bigger_s
s=start_h.to_i*60+start_m.to_i
e=end_h.to_i*60+end_m.to_i
errors.add(:end_h,"End must be bigger than start") unless e > s
end
end
rtimespan模型:
class Rtimespan < ActiveRecord::Base
belongs_to :timespan
belongs_to :subgroup
validates :subgroup, presence: true
validates :subgroup, presence: true
end
子组模型:
class Subgroup < ActiveRecord::Base
belongs_to :group
has_many :timespans
has_many :memberships
has_many :users, through: :memberships
has_many :translations
has_many :actioncodes, through: :translations
has_many :entries
has_many :rules
validates :name, presence: true, uniqueness: true
validates :group_id, presence: true
has_many :rtimespans
has_many :timespans, through: :rtimespans
end
无论如何,当我想在这段关系上打电话时,我得到了这个错误。
ActiveRecord::StatementInvalid in Subgroups#show
Showing C:/xampp/htdocs/fluxcapacitor/app/views/subgroups/show.html.erb where line #40 raised:
SQLite3::SQLException: no such column: rtimespans.subgroup_id: SELECT "timespans".* FROM "timespans" INNER JOIN "rtimespans" ON "timespans"."id" = "rtimespans"."timespan_id" WHERE "rtimespans"."subgroup_id" = ?
任何人都可以告诉我,如何解决这个问题,或者至少告诉我,这个错误来自哪里?
答案 0 :(得分:2)
我会检查错误指示的迁移。要查看是否存在缺失列,请检查您的schema.rb以确保该列存在
答案 1 :(得分:0)
我假设错误是由于您在Subgroup
模型中两次提到与 timespans 的关系。
您已定义
has_many :timespans and
has_many :timespans, through: :rtimespans
请在模型中更正并检查。
答案 2 :(得分:0)
发现我的错误!我有一个“双ID ”:
create_table "rtimespans", force: true do |t|
t.integer "subgroup_id_id"
t.integer "timespan_id_id"
end
我创建了一个错误的迁移:
class CreateRtimespans < ActiveRecord::Migration
def change
create_table :rtimespans do |t|
t.belongs_to :subgroup_id
t.belongs_to :timespan_id
end
end
end
应该是:
class CreateRtimespans < ActiveRecord::Migration
def change
create_table :rtimespans do |t|
t.belongs_to :subgroup
t.belongs_to :timespan
end
end
end