嗨我想知道用户是否有办法更新他们已经写过的评论,我尝试使用cancan但遇到了一些问题,所以我宁愿发现是否有更简单的方法。这是评论控制器中“新”方法的代码
def new
if logged_in?
@review = Review.new(:film_id => params[:id], :name =>
User.find(session[:user_id]).name)
session[:return_to] = nil
else
session[:return_to] = request.url
redirect_to login_path, alert: "You must be logged in to write a review"
end
end
和'create'方法
def create
# use the class method 'new' with the parameter 'review', populated
# with values from a form
@review = Review.new(params[:review])
# attempt to save to the database, the new review instance variable
if @review.save
# use the class method 'find' with the id of the product of the
# saved review and assign this product object to the variable 'product'
film = Film.find(@review.film.id)
# redirect the reviewer to the show page of the product they reviewed,
# using the product variable, and send a notice indicating the review
# was successfully added
redirect_to film, notice: "Your review was successfully added"
else
# if the review could not be saved, return / render the new form
render action: "new"
end
end
如果用户已经为产品撰写评论,我希望用户编辑他们的评论。而不是同一个用户对同一产品进行两次评论。
答案 0 :(得分:0)
要更新记录,您应该使用update
操作,该操作是在用户提交edit
表单后请求的。
答案 1 :(得分:0)
让您的用户模型具有has_many / has_one:评论。并查看模型belongs_to:user。然后,如果您有任何类型的授权(并且您应该拥有,例如:设计),您将知道审核用户当前是否已登录用户。如果是,则渲染编辑按钮,否则不渲染。
同样根据CRUD惯例,您需要执行2项操作。首先是edit
和另一个update
。你可以在railsguides.com上阅读它。
答案 2 :(得分:0)
你可以将这样的东西分成create
方法:
# Assumes that your user names are unique
@review = Review.find_or_create_by_film_id_and_name(params[:review][:film_id], User.find(session[:user_id]).name)
@review.update_attributes(params[:review])
以下是
@review
实例变量Review
对象并将其分配给@review
@review
params[:review]
醇>
或者,以下语句将在不使用Rails find_or_create
便捷方法的情况下完成相同的操作:
user_name = User.find(session[:user_id]).name # To avoid two DB lookups below
@review = Review.find_by_film_id_and_name(params[:review][:film_id], user_name) || Review.new(:film_id => params[:review][:film_id], :name => user_name)
@review.update_attributes(params[:review])