在我的Rails应用程序中,它的工作原理类似于Pinterest,用户上传一个带有描述的图片(图书封面),他们可以“喜欢”另一个用户的书,这将把它添加到他们的个人资料中。但是,我希望描述文本作为一个建议,所以每个用户都应该写他们自己的推荐,即使书已经存在于网站上。
是否有可能在书页上添加一个表单,这样某人就可以在“喜欢”这本书时写一个新的描述,这样应用程序就可以创建一本包含所有属性的新书,只需复制一本新的描述即可。我需要javascript吗?
谢谢!
发布于 2014-06-15 07:01:59
has_many :通过
您需要使用has_many :through
连接模型
这就是所谓的many-to-many
关系(这意味着您可以通过repins
将many pins
与many users
联系起来)。HMT设置使您能够将自己的数据添加到连接记录中--让您有机会为每个回复创建所需的描述:
#app/model/pin.rb
Class Pin < ActiveRecord::Base
has_many :repins
has_many :users, through :repins
end
#app/models/repin.rb
Class Repin < ActiveRecord::Base
#fields - id | user_id | pin_id | description | created_at | updated_at
belongs_to :user
belongs_to :pin
end
#app/models/user.rb
Class User < ActiveRecord::Base
has_many :repins
has_many :pins, through: :repins
end
这样你就可以打电话:
@pin = Pin.find params[:id]
@pin.repins.each do |repin|
repin.description
end
或
@user = User.find params[:id]
@user.repins.each do |repin|
repin.description
end
https://stackoverflow.com/questions/24225500
复制相似问题