2013-02-21 86 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讀到它