在Ruby on Rails中更新用户评论

时间:2013-02-21 13:14:19

标签: ruby-on-rails

嗨我想知道用户是否有办法更新他们已经写过的评论,我尝试使用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

如果用户已经为产品撰写评论,我希望用户编辑他们的评论。而不是同一个用户对同一产品进行两次评论。

3 个答案:

答案 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])

以下是

  1. 检查用户是否为电影制作了评论
  2. 如果是,请将现有评论分配给@review实例变量
  3. 如果没有,请创建一个新的Review对象并将其分配给@review
  4. 使用@review
  5. 更新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])