📘

Favorite.newの省略形

2023/07/30に公開1

忘れやすいので、メモ✍️
以下2つのコードは同じ意味になる。

favorites_controller.erb


def create
	book = Book.find(params[:book_id])
	favorite = current_user.favorites.new(book_id: book.id)
	favorite.save
	redirect_to books_path
end

def create
	book = Book.find(params[:book_id])
	favorite = Favorite.new
	favorite.user_id = current_user.id
	favorite.book_id = book.id
	favorite.save
	redirect_to books_path
end

Discussion

NanaNana

commentsバージョンはこちら

def create
    book = Book.find(params[:book_id])
    comment = current_user.book_comments.new(book_comment_params)
    comment.book_id = book.id
    comment.save
    redirect_back(fallback_location: root_path)
end
def create
 book = Book.find(params[:id])
 comment = Comment.new(book_comment_params)
 comment.user_id = current_user.id
 comment.book_id = book.id
 comment.save
 redirect_back(fallback_location: root_path)
end