我很难将评论与当前用户相关联。这是我的模特:
用户模型:
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email, :first_name
validates_uniqueness_of :email
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
评论模型:
class Review < ActiveRecord::Base
belongs_to :venue
belongs_to :user
end
场地模型:
class Venue < ActiveRecord::Base
has_many :reviews
has_many :menu_items
accepts_nested_attributes_for :reviews
end
查看控制器:
class ReviewsController < ApplicationController
def create
@venue = Venue.find(params[:venue_id])
@review = @venue.reviews.create(review_params)
if @review.save
redirect_to venue_path(@venue)
else
end
end
private
def review_params
params.require(:review).permit(:title, :body, :rating)
end
end
当前用户为场地创建新评价时,只需要一种方法将评论与当前用户相关联。
我按照这里的教程从头开始进行身份验证:
http://railscasts.com/episodes/250-authentication-from-scratch
我在发布之前咨询了以下内容,但无法弄清楚:
Rails: Associate posts with user and location
Associate user_id to the comment model?
Devise how to associate current user to post?
非常感谢任何帮助,谢谢!
答案 0 :(得分:1)
所以你想要的是在两个范围内一次创建一个新的review
:@venue.reviews
和current_user.reviews
)。 哦,坚持,后者甚至没有定义?我们首先在User
上定义:
has_many :reviews
然后,而不只是@venue.reviews
使用两个范围的组合:
@venue.reviews.merge(current_user.reviews).create(review_params)
# ^----------------this one----------------^
...并且创建的对象将具有两者的属性,除非它们是冲突的,在这种情况下后一个范围将优先。