How to save using the Mercury editor - ruby-on-rails

I want to get the save function in the Mercury editor working but to no avail.
I have a model to save the page, title and content.
mercury.js:
$(window).bind('mercury:ready', function() {
var link = $('#mercury_iframe').contents().find('#edit_link');
Mercury.saveURL = link.data('save-url');
link.hide();
});
$(window).bind('mercury:saved', function() {
window.location = window.location.href.replace(/\/editor\//i, '/');
});
static_pages_controller.rb:
def update
#static_page = StaticPage.find(params[:id])
#static_page.page = params[:page]
#static_page.title = params[:content][:aboutContainer][:value][:about_title][:value]
#static_page.content = params[:content][:aboutContainer][:value][:about_content][:value]
#static_page.save!
render plain: ''
end
about.html.erb:
<% provide(:title, 'About') %>
<div class="container" id="aboutContainer" data-mercury="full">
<h1 id="about_title"><%= raw #static_page.title %></h1>
<div class="col-sm-12">
<p id="description about_content"><%= raw #static_page.content %></p>
</div>
<p><%= link_to "Edit Page", "/editor" + request.path, id: "edit_link",
data: {save_url: static_page_update_path(#static_page)} %></p>
</div>

Ok, so i basically realised that I needed a show action so I can grab records from the model and save to the #static_page object
I was following this guide: http://railscasts.com/episodes/296-mercury-editor?autoplay=true
Please note I had to change my routes to using those in the link (or similar routes to them) and had to place them before the default mercury routes and had to change:
#static_page.title = params[:content][:aboutContainer][:value][:about_title][:value]
#static_page.content = params[:content][:aboutContainer][:value][:about_content][:value]
to:
#static_page.title = params[:content][:about_title][:value]
#static_page.content = params[:content][:about_content][:value]
I then removed the class 'container' div in about.html.erb and moved all the code to show.html.erb not needing about.html.erb.

Related

How to infinite scroll with Kaminari in rails 6?

I am looking for solution for infinite scroll with Kaminari in my project, but it still does not work as expected.
In my home page have view for render post:
<div class="home_post_tab_content">
<%if #posts.present?%>
<div id="home_post_infinite_scroll">
<%= render #posts %>
</div>
<%if #posts.total_count > 10%>
<div class="home_post_pagination_button" id="home_post_pagination">
<%= link_to_next_page(#posts, 'Xem thêm', :remote => true) %>
</div>
<%end%>
<%end%>
</div>
Controller:
respond_to do |format|
format.html {}
format.js
end
Script file:
// Append new data
$("<%=j render #posts %>").appendTo($("#home_post_infinite_scroll"));
// Update pagination link
<% if #posts.last_page? %>
$('#home_post_pagination').remove();
<% else %>
$('#home_post_pagination').html("<%=j link_to_next_page(#posts, 'See more', :remote => true) %>");
<% end %>
Q: How can I trigger the next button when user scrolls in end of page (jquery or JS...)?
Or, If any one has another solution for infinite scroll please let me know. Thanks so much!
I found the solution for resolve it:
<script>
$(document).on('turbolinks:load', function() {
$(window).scroll(function() {
var next_url = $("#home_post_pagination a[rel='next']").attr('href');
if (next_url && ($(window).scrollTop() > ($(document).height() - $(window).height() - 5000))) {
$('#home_post_pagination').show();
$('#home_post_pagination').html('<a>Loading...</a>');
$.getScript(next_url);
return;
}
});
return $(window).scroll();
});
</script>
The $.getScript(next_url) will be trigger next button on scroll

Ajax Call for load more button in Rails

I want to do load data with load more button. I have implemented like this in posts/index.html.erb:
<div id="posts">
<h1>Posts</h1>
<%= render #posts %>
</div>
<div class="load-more-container">
<%= link_to "Load More", posts_index_path, class: "load-more" %>
</div>
Then _post.html.erb:
<div class="post">
<h2><%= post.title %></h2>
<p><%= post.body %></p>
</div>
Then index.js.erb:
$('#posts').append('<%= escape_javascript render(#posts) %>');
In posts_controller I wrote like this:
##count=2
def index
if params[:id]
#posts = Post.where('id < ?', params[:id])
else
#posts = Post.limit(##count)
end
##count+=2
respond_to do |format|
format.html
format.js
end
end
Then in application.js:
$(document).ready(function () {
$('a.load-more').click(function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $(this).attr('href'),
dataType: "script",
success: function () {
$('.load-more').show();
}
});
});
});
I am getting first 2 data:
Post1
Post2
load more
when clicking on load more I am getting like this:
Post1
Post2
Post1
Post2
Post3
Post4
but I want only:
Post1
Post2
Post3
Post4
Could anyone please help me. Thanks in advance.
Since you are fetching all records everytime click on loadmore button, Dont append result and overwrite with html
$('#posts').html('<%= escape_javascript render(#posts) %>');
In your controller, you replace
#posts = Post.limit(##count) => #posts = Post.limit(2).offset(##count - 2)
if you want load more 2 artices.

Ruby on Rails select2 AJAX/JQuery - passing a parameter to controller not working

I'm trying to make a Job descriptions (JD) page to compare between a choose JDs.
My main page will have a field to select some jobs, and a button/link to show the selected jobs details in a table below the selection field using select2 with RoR, as in the image
Job descriptions Viewer .
My issue is that I cannot pass the selected Jobs IDs to the controller, and I get this message:
Completed 406 Not Acceptable in 20ms (ActiveRecord: 0.0ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/job_descriptions_controller.rb:81:in `updateJobs'
My controller method :
def updateJobs
#selected = JobDescription.where(id: params[:selectJdField2])
respond_to do |format|
format.js
format.html
end
end
The main View (jdComparison.html.erb) will render two partials
<h1>Listing Job Descriptions</h1>
<%= render 'sidebar' %>
<div class="clearfix"></div>
<div>
<%= render partial: 'item_list', locals: { job_desc: #job_descriptions} %>
</div>
The _sidebar.html.erb partial has selet2 field and a link to refresh the Jds that called "Find Link":
<div class="col-sm-8">
list of JDs:
<%= select_tag "selectJdField", options_from_collection_for_select(#job_descriptions, :id, :job_title), { :multiple => true } %>
</div>
<%= link_to "Find Link", updateJobs_path(#job_descriptions), :remote => true %>
<script>
$(document).ready(function() { $("#selectJdField").select2(); });
</script>
The _item_list.html.erb partial will view all JDs have been chosen in the select2 field:
<div>
<table>
<thead>
<tr>
<th>Job title</th>
<th>Department</th>
</tr>
</thead>
<tbody>
<% job_desc.each do |job_description| %>
<tr>
<td><%= job_description.job_title %></td>
<td><%= job_description.department %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
updateJobs.js.erb, should refresh the JDs list when I click the "Find Link" button (I think my first issue is here)
$("#div_id").html("<%= escape_javascript(render partial: 'item_list', locals: { job_desc: #selected}) %>")
The JS file (I think my second issue is here):
$ ->
updateLists = () ->
$.ajax
url:'updateJobs'
type: 'post'
dataType: 'html'
format: 'js'
data: {
selectJdField2 : $('#selectJdField').val()
}
The routes:
get 'updateJobs' => 'job_descriptions#updateJobs'
post 'updateJobs' => 'job_descriptions#updateJobs'
When I replace the controller method with this:
def updateJobs
#selected = JobDescription.where(id: 1)
end
it will give me the details of JD number 1 after clicking the Find Link. Kindly, I need your help..
This what I've done to make it works:
I have relapsed the "Find Link" with a normal button:
<button id="btnFind">Find</button>
I added "id" to the first div in _item_list.html.erb partial
<div id = "div_id">
In js file:
$ ->
$(document).on 'change', '#selectJdField', (evt) ->
updateLists()
$(document).on 'click', "#btnFind", (evt) ->
updateLists()
updateLists = () ->
$.ajax '/updateJobs',
type: 'GET'
dataType: 'script'
data: {
selectJdField2 : $('#selectJdField').val()
}
and I didn't need (post 'updateJobs') in the routes file.. Now, everything work fine...Thank you "Venkat Ch"

Rails: passing an instance variable to different controller through a partial

In Category view I have:
<ul>
<% #category.subcategories.each do |subcategory| %>
<li>
<h6>
<%if subcategory.has_topic_headings? %>
<%= link_to subcategory.name, { controller: 'subcategories',
action: 'show_topic_headings',
category_id: subcategory.category_id,
id: subcategory.id
}, data: 'topic_heading_link',
remote: true %>
<% else %>
<%= link_to subcategory.name, subcategory %>
<% end %>
</h6>
<hr>
</li>
<% end %>
</ul>
In application.js:
/* slides in the subcategory menu or the content */
$('.category-menu a').on(
'click',
function(e) {
if ($(this).attr('data')) {
/* make submenu visible */
$('.stretched.nav.row > .slider').animate({left:'-62.5em'});
e.preventDefault();
}
else {
/* make content visible */
$('.stretched.main.row > .slider').animate({left:'-62.5em'});
e.preventDefault();
}
}
);
In subcategories_controller.rb
def show_topic_headings
respond_to :js
#subcategory = Subcategory.find(params[:id])
end
And in subcategories/show_topic_heading I have:
$('.subcategory-menu').html( "<%= escape_javascript( render( partial: "layouts/topic_headings", locals: { subcategory: #subcategory} ) ) %>" );
Clicking on the active link, .subcategory-menu should be populated with the correct content and the div containing should slide in. But the content only appears if it's static (for example, if I put a string instead of a reference to #subcategory). Please note that the view in which I am inserting the subcategory partial is a category view.
The problem lies in the subcategories_controller:
respond_to, not the function itself, generates the partial. Therefore the instance variable needs to be declared before calling respond_to
def show_topic_headings
#subcategory = Subcategory.find(params[:id])
respond_to :js
end

Dynamic Partial Based on Select Box - Rails 2.3.5

I've edited my request to hopefully be clearer. I need to render a partial dynamically based on a previous selection box.
REQUEST belongs to PRODUCT
PRODUCT belongs to CATEGORY
CATEGORY has many PRODUCTS
PRODUCT has many REQUESTS
User hits form: create_request.html.erb
User selects a category, then the products select list is populated (like Railscast 88 - dynamic select boxes)
What I now need is to render different partial forms based on which product is selected. I suck at jquery.
create_request.html.erb:
<%= javascript_include_tag "dynamic_products.js" %>
<% form_for :request, :url => {:controller => :requests, :action => :create_request, :id => params[:id]} do |f| %>
<label>Select Category:</label>
<%= select( "request", "category_id", Category.find( :all).collect { |c| [c.name, c.id] })%></br>
<div id="product_field">
<label>Select Product</label>
<%= select( "request", "product_id", Product.find( :all).collect { |p| [p.name, p.id] })%></br>
</div>
#### and here is where I need help:
#### if request.product_id = 1, render partial _form1
#### if request.product_id = 2, render partial _form2
<button type="submit">Submit</button>
<% end %>
dynamic_products.js.erb:
var products = new Array();
<% for product in #products -%>
products.push(new Array(<%= product.category_id %>, '<%=h product.name %>', <%= product.id %>, <%= product.active %>));
products.sort()
<% end -%>
function categorySelected() {
category_id = $('request_category_id').getValue();
options = $('request_product_id').options;
options.length = 1;
products.each(function(product) {
if (product[0] == category_id && product[3] == 1) {
options[options.length] = new Option(product[1], product[2]);
}
});
if (options.length == 1) {
$('product_field').hide();
} else {
$('product_field').show();
}
}
document.observe('dom:loaded', function() {
categorySelected();
$('request_category_id').observe('change', categorySelected);
});
one reminder first before we start. I'm not sure about this but I think request is a reserved word in rails.
JS
this just observes the dropdown and performs an ajax call
$(document).ready(function() {
$('#request_product_id').change(function() {
$.ajax({ url: '/products/' + this.value + '/form_partial' });
});
});
ROUTES
nothing fancy here either. Just setting up a route where the ajax will go to when it is triggered
resources :products do
get :form_partial, on: :member
end
CONTROLLER
we just fetch the product using :id which is passed from ajax
def form_partial
#product = Product.find params[:id]
end
JS TEMPLATE
you need to create a form_partial.js.erb which will render the partial depending on the product. The code below appends the partial after the product_field div
# app/views/products/form_partial.js.erb
$('#product_partial').remove();
<% if #product.id == 1 %>
$('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial1') %></div>');
<% else %>
$('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial2') %></div>');
<% end %>
UPDATE: for rails 2.x
we just need to change the routes and the js template in order for this to run on rails 2.x
ROUTES 2.x
map.resources :products, member: { form_partial: :get }
JS TEMPLATE 2.x
if I remember correctly, the file should be named form_partial.js.rjs. This will give you a page variable which you can use to add js.
# app/views/products/form_partial.js.rjs
page << "$('#product_partial').remove();"
page << "<% if #product.id == 1 %>"
page << " $('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial1') %></div>');"
page << "<% else %>"
page << " $('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial2') %></div>');"
page << "<% end %>"

Resources