Tim Tim - 6 months ago 20
Ruby Question

Flash message in AJAX rendering

I have a

Products
and product
Reviews
controller. Im trying to display a Flash message (
"Your review is under review for approval"
) in my AJAX rendering when a review is created. Not sure how do i go about doing so.


Review Controller


def create
@product = Product.find(params[:product_id])
@review = Review.new(review_params)
@review.user = current_user
@review.product = @product
respond_to do |format|
if @review.save
format.html { redirect_to product_path(@product), flash[:notice]="Your review is under review for approval" }
format.js {render :create_success}
else
format.html { render "products/show" }
format.js {render :create_failure}
end
end
end



create_success.js.erb


$("#reviews").prepend("<%= j render '/reviews/review', review: @review %>");
<% @review = Review.new %>
$("#new_review").replaceWith("<%= j render 'review_form' %>")



index.html.erb


<div class="reviews" id="<%= dom_id(review)%>">
</div>

<%= simple_form_for [@product, @review], remote: true do |f| %>
<div class="form-group">
<%= f.input :review_comment, placeholder: "Let us know what you think here..."%>
</div>
<div>
<%= f.submit "Submit", class: "btn review-form-btn" %>
</div>
<% end %>

dkp dkp
Answer

Step-1:

Add an element to DOM as follows:

<div id="flash_notice"></div>

Step-2:

Render flash message to DOM in create.js.erb :

$("#flash_notice").html("Your review is under review for approval");
Comments