#Actions with ajax http://code.tutsplus.com/tutorials/using-unobtrusive-javascript-and-ajax-with-rails-3--net-15243 ##Destroy Для того, чтобы удалить что-либо без перезагрузки страницы следует:
-
добавить remote: true к хелперу link_to во вью:
..\blog_web_application\app\views\comments\_comment.html.haml = link_to "Destroy", user_post_comment_path(:post_id => @post, :parent_id => comment), :confirm => "Are you sure?", :method => :delete, remote: true if comment.user_id == current_user.id || comment.post.user_id == current_user.id
-
добавить format.js { render layout: false } в контроллер comments экшена destroy:
..\blog_web_application\app\controllers\comments_controller.rb def destroy @comment.destroy respond_to do |format| format.html { redirect_to user_post_path(@comment.post.user_id, @comment.post_id), notice: 'Comment was successfully destroyed.' } format.json { head :no_content } format.js { render layout: false } end
-
создать новую вью destroy.js.erb и наполнить ее кодом:
..\blog_web_application\app\views\comments\destroy.js.erb $("#<%[email protected]%>").hide();
Модель кода $("#<%[email protected]%>").hide(); выгладит так - $("SELECTOR").operation();.
$("SELECTOR") принимает из HTML значения либо класс, либо #id, либо тег
.operation(); подразумевает метод, который нужно поставить. ** операции ищи в гугле jQuery how to hide (any other operation) element
В нашем случае мы приняли решение брать #id для элемента, который мы хотим скрыть на странице и применили к нему метод hide();.
Чтобы это стало возможным, мы каждому тегу li присвоили свой уникальный id:
..\blog_web_application\app\views\comments\_comment.html.haml
[email protected] do |comment|
%br
%li{:id => comment.id}
= comment.created_at.strftime("%B %d, %Y")
= comment.content
= link_to "Reply", new_user_post_comment_path(:post_id => @post, :parent_id => comment)
= link_to "Destroy", user_post_comment_path(:post_id => @post, :parent_id => comment),
:confirm => "Are you sure?", :method => :delete, remote: true
if comment.user_id == current_user.id || comment.post.user_id == current_user.id
@comment мы взяли из экшена destroy.
##Create Для того, чтобы создать что-либо без перезагрузки страницы следует:
-
добавить remote: true к хелперу horizontal_simple_form_for во вью:
..\something\_form.html.haml = horizontal_simple_form_for(@subscriber, :url => subscribe_create_path, :method => :post, html: { class: 'form-horizontal' }, remote: @data) do |f|
@data - это переменная, которая находится в соответствующем вьюхе контроллере и может быть true либо false (если мы не хотим включать ajax, то @data = false)
-
создать файл create.js.erb в той же папке с кодом:
..\something\create.js.erb $("#messages").prepend("<li><%= escape_javascript( render @message, locals: {message: @message}) %></li>");
Метод prepend "ставит" в верх списка только что созданную запись, остальное можно прочесть здесь: http://stackoverflow.com/questions/21336060/rails-escape-javascript-breaks-javascript-used-in-partial Так же, после создания, мы можем сделать возникающую надпись в любом div, например:
..\something\demo.html.haml
...
=form_tag(subscribe_create_path, remote: true, :method => "post", :id => "beta_subscriber_form") do
.form-group
.input-group{:style => "width: 300px; margin: auto;"}
%input.form-control{:name=>'beta_subscriber[email]', :placeholder => "[email protected]", :type => "email", :style => "border-radius: 0px !important; border: none; border-color: transparent; outline: 0; background-color: #494949;"}
%span.input-group-btn
<input type="submit" value="Join Beta" class="btn btn-primary" style="border-radius: 0px !important;">
%br
#beta_subscribe_result
...
..\something\create.js.erb
$("#beta_subscribe_result").html("Yahoo");
или можно сделать так, чтобы показалась картинка, которая находится в ../app/assets/images/done3.png с подписью, а сама форма пропала. Для примера приведен код ниже, в нем есть ДВА ОДИНАКОВЫХ ПО СОДЕРЖАНИЮ БЛОКА, но у каждого блока должен быть СВОЙ УНИКАЛЬНЫЙ ID!!!
..\something\demo.html.haml
...
#beta_subscribe_result_up.text-center(style="display:none;")
#to_hide_up
%p#main_def_text.text-center
We'd be happy to keep you posted
%br
about the beta program and launch
%h3#main_def_text.text-center{:style => "font-size: 10pt !important; padding: 0px !important; margin: 0px !important; "}
(your email won't be used for anything else.)
%br
#inp_block.row
.col-md-12
=form_tag(subscribe_create_path, remote: true, :method => "post", :id => "beta_subscriber_form") do
.form-group
.input-group{:style => "width: 300px; margin: auto;"}
%input.form-control{:name=>'beta_subscriber[email]', :placeholder => "[email protected]", :type => "email", :style => "border-radius: 0px !important; border: none; border-color: transparent; outline: 0; background-color: #494949;"}
%span.input-group-btn
<input type="submit" value="Join Beta" class="btn btn-primary" style="border-radius: 0px !important;">
...
#beta_subscribe_result_down.text-center(style="display:none;")
#to_hide_down
%h1
Want to stay updated?
%h3{:style => "padding-top: 0px; padding-bottom: 10px; margin: 5px; font-size:10pt !important;"}
(your email won't be used for anything else.)
#inp_block.row
.col-md-12
=form_tag(subscribe_create_path, remote: true, :method => "post", :id => "beta_subscriber_form") do
.form-group
.input-group{:style => "width: 300px; margin: auto;"}
%input.form-control{:name=>'beta_subscriber[email]', :placeholder => "[email protected]", :type => "email", :style => "border-radius: 0px !important; border: none; border-color: transparent; outline: 0; background-color: #494949;"}
%span.input-group-btn
<input type="submit" value="Join Beta" class="btn btn-primary" style="border-radius: 0px !important;">
...
..\something\create.js.erb
$("#to_hide_up").hide();
$("#to_hide_down").hide();
$("#beta_subscribe_result_up").html(" <h3> <%=escape_javascript(image_tag('done3.png')) %> <br>" + "Thanks! <br> We'll concact you as soon as possible</h3>");
$("#beta_subscribe_result_down").html(" <h3> <%=escape_javascript(image_tag('done3.png')) %> <br>" + "Thanks! <br> We'll concact you as soon as possible</h3>");
$("#beta_subscribe_result_up").show();
$("#beta_subscribe_result_down").show();