我有一个User模型和一个Book模型与Like模型相结合。
class Book < ActiveRecord::Base
belongs_to :user
# the like associations
has_many :likes
has_many :liking_users, :through => :likes, :source => :user
class User < ActiveRecord::Base
has_many :books
# the like associations
has_many :likes
has_many :liked_books, :through => :likes, :source => :book
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :book
我想在Like模型中添加一个属性,所以现在用户可以像书一样将它添加到他们的个人资料中,我希望用户能够写一个推荐。
我为Like(加入)模型生成了属性Recommendation:text,但我不确定如何将其添加到视图中,以便用户可以编写与Like(以及该书和用户)相关联的推荐。
我正在看这篇文章 - Rails has_many :through Find by Extra Attributes in Join Model - 它描述了类似的内容,但没有解释如何在视图中实现这一点。
如果你能指出我正确的方向,请告诉我。谢谢!
答案 0 :(得分:0)
我认为您应该根据Like模型为本建议书创建一个单独的模型:
class Book < ActiveRecord::Base
belongs_to :user
has_many :comments
has_many :commenters, :through => :comments, :source => :user
class User < ActiveRecord::Base
has_many :books
has_many :comments
has_many :commented_books, :through => :comments, :source => :book
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :book
然后,为一本书创建评论的逻辑:
# Books Controller
def show
@book = Book.find(params[:id])
@comment = @book.comments.build
end
# show view of the book
form_for @comment do |form|
form.hidden_field :user_id, value: current_user.id
form.hidden_field :book_id
form.text_area :content # the name of the attribute for the content of the comment
form.submit "Post comment!"
end
列出特定用户的所有评论:
# users controller (profile page)
def show
@user = User.find(params[:id])
end
# show view of Users
@user.comments.includes(:book).each do |comment|
"Comment on the book '#{comment.book.name}' :"
comment.content
end
答案 1 :(得分:0)
我认为类似的功能与ajax一起使用? (远程::真或纯javascript) 您可以附加一个表单,其中包含您的请求的响应以及新的id的id,并再次通过ajax请求处理建议