Backbone, stackmob sub-models - render to html - templates

I am really new to backbone so any help on this would be awesome, even just to point me in the direction of some resources related to this.
I have tried to create a fiddle but it won't work the same as on my machine: http://jsfiddle.net/Wh2H5/
Basically what I need to do is render the array of objects(see the image below) as parts of the template.
This is the view I am rendering:
var ListView = Backbone.View.extend({
tagName: 'ul',
className : 'nav nav-list',
initialize: function() {
this.collection.bind('all', this.render,this);
this.template = _.template($('#item-list').html());
},
render:function (eventName) {
$(".bike_list ul").empty();
this.collection.each(function(bike){
this.$el.append(this.template(bike.toJSON()));
},this);
return this;
}
});
So to see the problem copy the code from this fiddle and paste it to a html document.

I can highly recommend Marionette on top of Backbone to save you a lot of boiler plate for managing Views.

You can in-line javascript in your template and loop through the part_rel array and render the objects accordingly. The code would look like:
<% _.each(part_rel,function(part) { %>
<li>
Part Name: <%= part.name %>
After Hp: <%= part.after_hp %>
</li>
<% }); %>
Here is the code added to your template:
<script type="text/template" id="item-list">
<li class="<%= model %>">
<strong>Bike ID:</strong> <%= bikes_id %><br>
<strong>Model:</strong> <%= model %><br>
<strong>Before cc:</strong> <%= before_cc %><br>
<strong>Before ci:</strong> <%= before_ci %><br>
<strong>Before HP:</strong> <%= before_hp %><br>
<strong>Before torque:</strong><%= before_torque %><br>
<strong>Related parts:</strong><ol>
<% _.each(part_rel,function(part) { %>
<li>
Part Name: <%= part.name %>
After Hp: <%= part.after_hp %>
</li>
<% }); %>
</ol>
<br><br>
</li>
</script>
Read up on underscore's documentation for template. Also, here is a working example, http://jsfiddle.net/mFwsK/.

Related

Ruby on rails Tutorial Missing partial articles/_form

Hi I have just started using Ruby on rails and have been following the tutorial # http://guides.rubyonrails.org/getting_started.html.
The problem I have got, is with 5.12 Using partials to clean up duplication in views.
I am getting the error ActionView::MissingTemplate in Articles#new.
It is looking for _form.html.erb , which is in the directory /app/views/articles/. So not sure why it cannot find it.
articles controller for new
def new
#article = Article.new
end
articles view for new
<h1>New article</h1>
<%= render 'form' %>
<%= link_to 'Back', articles_path %>
articles view for _form.html.erb
<%= form_for #article do |f| %>
<% if #article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(#article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% #article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
< % end %>
Any help would be appreciated, need to know how to solve before going on to next part.
Hi I have got it to work by renaming _form.html.erb to_form as the error is looking for /apps/views/_form. I don't know if this is the correct way to solve the problem, as its says in the tutorial to name the file _form.html.erb.
would this cause issues in future doing it this way?
Check the file name, maybe you copied it wrong
I changed the file name to '_form.erb' and it worked. Still puzzled why the full suffix of 'html.erb' didn't work.

CKEditor cktext_area only shows up when refreshing page (Rails 4/Heroku)

My local version runs CKEditor fine.
Edit: Local version does the same thing.
It's runs on heroku as well, but when I first load my create blog post page, the cktext_area simply shows up as a normal text_area box. When I refresh the page, the ck_textarea shows up like it is supposed to.
I'm not sure why this is happening.
This is using rails 4.
Here's my application layout
<!DOCTYPE html>
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= render 'layouts/header' %>
<div class="container">
<% if notice %>
<p class="alert alert-success"><%= notice %></p>
<% end %>
<% if alert %>
<p class="alert alert-danger"><%= alert %></p>
<% end %>
<%= yield %>
<%= render 'layouts/footer' %>
</div>
</body>
</html>
Here's my application.js
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require ckeditor/init
//= require_tree .
And my blog create form
<%= form_for #article do |f| %>
<% if #article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(#article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% #article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title, :size=>'50' %>
</p>
<p>
<%= f.label :text %><br>
<%= f.cktext_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
I know I'm late to the party, but may be it will help someone.
The problem is that ckeditor isn't initialized after visiting a turbolinks link. So the solution is to reinitialize ckeditor every time turbolinks loads pages.
This could be done using turbolinks callback turbolinks:load (page:load for old versions)
The second problem is that turbolinks:load fires every time even on document ready event. So I have to check somehow if ckeditor is initializes or I'll get The editor instance ... is already attached to the provided element.
The final code will be:
$(document).on('turbolinks:load', function() {
$('.ckeditor:visible').each(function() {
var id = $(this).attr('id');
if (!CKEDITOR.instances[id]) {
CKEDITOR.replace(id);
}});
});
OK. Well. This isn't a complete solution, but removing turbolinks solves this issue. I certainly don't need turbolinks for my project, but it would eventually be nice to find a solution that works including turbolinks.
removed //= require turbolinks from application.js
It would seem CKEditor doesn't play nice with turbolinks. Instead of disabling turbolinks, I simply added a data: { 'no-turbolink' => true } to any link that contained a ckeditor.
For example, in my header I had a link to create a new blog post:
<%= link_to "Create New Blog Post", new_article_path, data: { 'no-turbolink'=>true} %>
This solved it for me, without completely removing turbolinks.

Adding space between labels and fields

In my Rails app, the labels for the fields on the login page are way too close to the fields themselves, making it look cramped. I want to add space between them, but am not sure how.
I have Rails 4 with simple_form, bootstrap 3, and devise installed.
This is my app/views/devise/sessions/new.html.erb code:
<div class="row">
<div class="col-xs-4">
<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name), html: {class: "well"}) do |f| %>
<fieldset>
<legend>Log in</legend>
<%= f.input :email %>
<%= f.input :password %>
<% if devise_mapping.rememberable? -%>
<div class="field">
<%= f.input :remember_me, as: :boolean %>
</div>
</fieldset>
<% end -%>
<div class="actions">
<%= f.button :submit, "Log in" %>
</div>
<% end %>
<%= render "devise/shared/links" %>
</div>
<div class="col-xs-8">
<h2>Signing in is easy and secure</h2>
</div>
</div>
And here is the entire github repo: https://github.com/yamilethmedina/wheels_registration
I've been looking in my bootstrap.css file and can't find relevant classes. What do you think I should do next?
You could add your own label with space after the custom label.
<%= f.input :email, label: 'Email ' %>
<%= f.input :password, label: 'Password ' %>
Or you could use tools like chrome dev tools to inspect the label element to see what class the labels are given and then add some custom css. example .label-class { margin-right: 10px; }

creating a record in a table automatically after saving the other record in tne other table rails4

I still novice with RoR. My mission is to add examplaries according to the number of exemplary inserted in the form of book, knowing that i have a book table and an examplary table and the relationship in between is a book has_many exemplaries and an exemplary belong_to a book.
This is my attempt:
in books_controller.rb
method create:
def create
#book= Book.new(book_params)
if #book.save
#book.nbr_exemplaires.times do |i|
#exemplaire= Exemplaire.create(book_id: #book.id, state: 0 )
end
flash[:notice]='goood'
redirect_to admin_manage_path
else
flash[:alert]='ouups'
redirect_to root_url
end
end
private
def book_params
params.require(:book).permit(:title, :pages, :resume,:nbr_exemplaires, :has_exemplaires, :author_ids =>[], :subject_ids =>[])
end
book/new.html.erb:
<h1>Add new book</h1>
<%= form_for(#book) do |form| %>
<div> <%= form.label :title %><br>
<%= form.text_field :title %>
</div>
<div>
<%= form.label :pages %><br>
<%= form.number_field :pages %>
</div>
<div>
<%= form.label :resume %><br>
<%= form.text_area :resume %>
</div>
<div>
<p>select author from existing list</p><br>
<%= form.collection_select :author_ids, #authors, :id, :l_name, {:selected => 1}, {:name => 'book[author_ids][]'} %>
</div>
<div>
<p> Select subject from existing list</p><br>
<%= form.collection_select :subject_ids, #subjects, :id, :name, {:selected =>1}, {:name => 'book[subject_ids][]'} %>
</div>
<div>
<%= form.label :has_exemplaires? %>
<%= form.check_box :has_exemplaires,{}, 'Yes', 'No'%>
<div id="expl_details" style="display:none;">
<%= form.label :nbr_exemplaires %> <%= form.number_field :nbr_exemplaires %>
</div>
</div>
<%= form.submit "Submit" %>
<% end %>
<script type="text/javascript">
var checkbox = document.getElementById('book_has_exemplaires');
var details_div = document.getElementById('expl_details');
checkbox.onchange = function() {
if(this.checked) {
details_div.style['display'] = 'block';
} else {
details_div.style['display'] = 'none';
}
};
</script>
Then I would suggest something like this:
class Book < ActiveRecord::Base
has_many :exemplaires
attr_accessor :nbr_exemplaires
after_save :create_exemplaires
private
def create_exemplaires
nbr_exemplaires.times do
self.exemplaires.create()
end
end
If you actually have a column name 'nbr_exemplaires' in your table, you don't need the attr_accessor line. That is only if you won't be saving that as separate value in the DB.
I would use nested attributes, that way rails will create them automatically for you through the same form:
class Book < ActiveRecord::Base
has_many :exemplaires
accepts_nested_attributes_for :exemplaires, allow_destroy: true
This would allow to use the nested form builder in your view:
<%= form_for(#book) do |form| %>
<div><%= form.label :title %><br>
<%= form.text_field :title %>
</div>
<%= form.fields_for :exemplaires do |f| %>
<%= f.text_field :name %>
... more fields
<% end %>
You could then add some javascript to create a multiple nested forms:
<%= link_to_add_fields "Add Exemplarie", f, :answers %>
With this kind of setup, rails will automatically create all the associated objects in the same action with no additional code on the controller/model side. Here is a great railscasts on it:
http://railscasts.com/episodes/196-nested-model-form-revised
If you haven't subscribed, I suggest you do. It's the most useful rails resource I ever used when starting out and it costs only a few $ a month. Good luck!

Rails 4.0 link_to overlaying an image with a link

I have a thumbnail image that links to a blog post entry which is accompanied by a text title. The CSS shades the image slightly and when the user hovers over the image, it re-sizes the image slightly. The user can click on the title or on the thumbnail to take them to the entry.
I cannot get the overlay tag here:
to be generated within rails link_to
<%= link_to(:class=>"overlay overlay-primary", id: entry) %>
The image is part of a figure
<figure class="entry-thumbnail">
<!-- to disable lazy loading, remove data-src and data-src-retina -->
<% if entry.cover_photo_link.blank? %>
<%= image_tag "placeholder.gif" %>
<% else %>
<%= image_tag entry.cover_photo_link %>
<% end %>
<!--fallback for no javascript browsers-->
<noscript>
<% if entry.cover_photo_link.blank? %>
<%= image_tag "placeholder.gif" %>
<% else %>
<%= image_tag entry.cover_photo_link %>
<% end %>
</noscript>
</figure>
The full thumbnail codes is in this gist
How do I get the image to link to use link_to render this?
The solution was simple. Putting the a blank "" in link_to did the trick
<%= link_to "", entry, :class => "overlay overlay-primary" %>
renders:
<a class="overlay overlay-primary" href="/entries/5"></a>
This worked well.