Rails多态关联在模型中不可用

神公爵

我是新手,请耐心等待,我整天都在搜索此内容。抱歉,这是初学者的问题:)

我有一个定义了多态关联的模型:

class SocialLink < ActiveRecord::Base
  belongs_to :social, polymorphic: true
end

还有两个模型应该具有这种关联中的一种

class Staff < ActiveRecord::Base
  validates :name, presence: true
  belongs_to :establishment
  has_one :image, as: :imageable
  has_one :social_link, as: :social
end


class Establishment < ActiveRecord::Base
  validates :name, presence: true
  has_one :location
  has_one :social_link, as: :social
  has_many :staff

  accepts_nested_attributes_for :location
  accepts_nested_attributes_for :staff
end

编辑:社交链接的初始表创建迁移

class CreateSocialLinks < ActiveRecord::Migration
  def change
    create_table :social_links do |t|
      t.string :facebook
      t.string :twitter
      t.string :yelp
      t.string :google_plus
      t.string :youtube
      t.string :instagram
      t.string :linkedin

      t.timestamps null: false
    end
  end
end

为此创建了迁移(编辑:请注意,该表在迁移时已存在)

class AddSocialLinkReferenceToEstablishmentAndStaff < ActiveRecord::Migration
  def change
    add_reference :social_links, :social_links, polymorphic: true, index: true
  end
end


class UpdateSocialLinkReference < ActiveRecord::Migration
  def change
    remove_reference :social_links, :social_links
    add_reference :social_links, :social, polymorphic: true, index: true
  end
end

编辑:完成上述迁移后,social_id和social_type可用

#<SocialLink id: nil, facebook: nil, twitter: nil, yelp: nil, google_plus: nil, youtube: nil, instagram: nil, linkedin: nil, created_at: nil, updated_at: nil, social_id: nil, social_type: nil> 

但是,由于某种原因,两个模型都无法使用该关联。我无法看到自己做错了什么,似乎已将其设置为与正在运行的图像模型上的另一个多态关联相同

这个正在工作

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

谢谢或帮助!

神公爵

问题是我试图访问具有多态名称的关联,而不仅仅是使用模型名称。而不是执行staff.social,我应该使用staff.social_link。我对此感到困惑。

对困惑感到抱歉

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

模型关联在Rails中调用

来自分类Dev

将所有模型关联在Rails上的ruby中

来自分类Dev

ExecJS :: Runtime在Rails中不可用

来自分类Dev

用 TensorFlow 训练的模型在 Django 中不可用

来自分类Dev

Rails 多态关联多模型

来自分类Dev

Rails 4-清单JS在AJAX中不可用

来自分类Dev

rails - FactoryGirl 持久化的对象在 Controller 中不可用

来自分类Dev

Rails中同一模型上的多个多态关联

来自分类Dev

尽管已包含关注模块,但该模型在模型中仍不可用(NoMethodError)

来自分类Dev

测试Rails中的多态关联

来自分类Dev

测试Rails中的多态关联

来自分类Dev

AngularJS:http调用中的模型数据在指令中不可用

来自分类Dev

用FactoryGirl创建的模型在控制器中不可用

来自分类Dev

模型不可用于ViewSettingsCustomItem中的自定义控件

来自分类Dev

模型不可用于ViewSettingsCustomItem中的自定义控件

来自分类Dev

Rails多态关联在控制台中显示但不在视图中

来自分类Dev

IPython在Spyder中不可用

来自分类Dev

范围变量在模板中不可用

来自分类Dev

在Swift 3中`curveEaseInOut`不可用

来自分类Dev

会话在IHttpModule中不可用

来自分类Dev

jQuery($)在模块文件中不可用

来自分类Dev

OSTYPE在Shell脚本中不可用

来自分类Dev

解决$ injector中不可用的对象

来自分类Dev

TestFlight Beta中的不可用消息

来自分类Dev

变量在脚本标签中不可用

来自分类Dev

点子包在conda中不可用

来自分类Dev

PWP类在UWP中不可用

来自分类Dev

auth在模块中不可用

来自分类Dev

.cs文件中的对象不可用