验证连接模型上是否存在列

时间:2014-03-06 15:12:32

标签: ruby-on-rails

我认为这是一个相当普遍的问题,但我找不到解决方案。我的域名有两个模型,公司和ExternalLink(Facebook或Twitter等社交媒体提供商的代表)。联接模型CompaniesExternalLink具有社交媒体帐户的直接URL(即http://www.facebook.com/goldmansachs)。我需要验证该URL的存在,但是在关联上创建了连接,该连接中断并返回ActiveRecord :: RecordInvalid

任何建议都会很棒。示例代码如下:

class Company < ActiveRecord::Base

    has_many :companies_external_links
    has_many :external_links, through: :companies_external_links, dependent: :destroy

end

class ExternalLink < ActiveRecord::Base

    has_many :companies_external_links
    has_many :companies, through: :companies_external_links, dependent: :destroy

end

class CompaniesExternalLink < ActiveRecord::Base
    validates :url, presence: true
    belongs_to :company
    belongs_to :external_link

    validates :external_link, uniqueness: {scope: :company_id}
end

schema.rb的相关部分

create_table "companies", force: true do |t|
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "name"
  t.string   "state"
  t.string   "logo"
  t.string   "slug"
  t.text     "description"
end

create_table "companies_external_links", force: true do |t|
  t.integer  "company_id"
  t.integer  "external_link_id"
  t.string   "url"
  t.datetime "created_at"
  t.datetime "updated_at"
end


create_table "external_links", force: true do |t|
  t.string   "source"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "icon"
end

0 个答案:

没有答案