我正在构建一个具有User
和Product
类的RoR应用程序。一个用户很多照片都可能是一个产品,但每个用户也必须有一个profile_picture
。Rails针对可能映射到不同模型类型的模型的活动记录关联
用户:
class User < ActiveRecord::Base
has_many :pictures
end
产品:
class Product < ActiveRecord::Base
has_many :pictures
end
我挣扎定义pictures
模型是目前:
class Picture < ActiveRecord::Base
has_one :user
has_one :product
end
留念的架构如下(时间戳为简洁起见):
create_table "pictures", force: true do |t|
t.string "image_url"
end
最后我不得不迁移到一个链接,资料图片添加到用户和产品
class AddPicturesToUsersAndWalks < ActiveRecord::Migration
def change
add_column :users, :profile_picture, :picture
add_column :products, :profile_picture, :picture
end
end
我已经通过http://guides.rubyonrails.org/association_basics.html和http://guides.rubyonrails.org/migrations.html看我不明白这些关系应该如何形成或数据库中的外键应该存储在哪里。
我无法查看用户或产品表的架构(rake db:migrate
在运行时没有抱怨),因为在架构文件中返回了以下错误(我认为这与在profile_picture
中都有关系,但我不确定如何进行:
# Could not dump table "users" because of following NoMethodError
# undefined method `[]' for nil:NilClass
请使用在轨道上4红宝石和sqlite3的数据库注意IM
谢谢,有没有办法链接配置文件图片,所以我可以访问它@ user.profile_picture呢? – user3576112 2014-08-31 18:43:28
@ user3576112看起来像'has_one:profile_picture,class_name:“Picture”,如::imageable'。相似的东西。 – 2014-08-31 19:45:32
谢谢,这将被保存为用户表中的引用还是只是一个picture_id? – user3576112 2014-08-31 19:53:04