2013-02-21 142 views
2

嗨,我想知道是否有一种方式,用户可以更新他们已经写的评论,我试着使用康康,但遇到了一些问题,所以我宁愿找出是否有一个更容易办法。这是从审查控制器在Ruby on Rails中更新用户评论

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 

“新”方法和“创造”的方法

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

你可能子像这样到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对象,并将其与params[:review]

可选地分配给@review

  • 更新@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]) 
    
  • +0

    辉煌!非常感谢 – 2013-02-24 15:18:11

    0

    要更新记录,您应该使用update操作,该操作在用户提交edit表单后请求。

    +0

    目前用户可以为同一产品写很多评论我最想要的是能够识别用户是否为产品编写了评论,而不是将评论转发给该评论的edit_path,而不是为该评论撰写新评论。同样的产品。 – 2013-02-21 13:29:03

    0

    让您的用户模型拥有has_many/has_one:reviews。和评论模型belongs_to:用户。然后,如果您有任何形式的授权(并且您应该拥有,例如:devise),您会知道审核的用户是否当前是登录用户。如果是的话再渲染编辑按钮,否则不渲染。

    同样根据CRUD约定,您需要2个动作。首先它的edit和另一个update。您可以在railsguides.com读到它