how to individualize each post? (Ruby on Rails) - ruby-on-rails

On each user profile (localhost:3000/users/username), there's a listing of posts that the user has made. I implemented facebox which is a jQuery-based lightbox to display images when clicked on. This is the code that I'm using for that:
<%= image_tag post.image_url(:thumb).to_s %>
The problem is that, if a user has made 5 posts, the same image is repeated 5 times when clicked on to display in facebox.
This is my show.html.erb where I render in #posts
<% provide(:title, #user.name) %>
<div class="row">
<aside class="span4">
<section>
<h1>
<%= gravatar_for #user %>
<%= #user.name %>
</h1>
</section>
<br>
</aside>
<br>
<div class="span10">
<%= render 'follow_form' if signed_in? %>
<% if #user.posts.empty? %>
<h3>Browse</h3>
<% end %>
<% if #user.posts.any? %>
<ol class="posts">
<%= render #posts %>
</ol>
<%= will_paginate #posts %>
<% end %>
</div>
</div>
and here's the _post.html.erb
<script src="/jquery.js" type="text/javascript"></script>
<link href="/src/facebox.css" media="screen" rel="stylesheet" type="text/css"/>
<script src="/src/facebox.js" type="text/javascript"></script>
<script language="javascript">
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox()
})
</script>
<li>
<span class="content"><%= simple_format(post.content) %></span>
<% if post.image.present? %>
<%= image_tag post.image_url(:thumb).to_s %>
<br>
<% else %>
<% end %>
<span class="timestamp">
Posted <%= time_ago_in_words(post.created_at) %> ago.
</span>
</li>

The javascript in _post.html.erb is included and executed once for each post. Therefore, if the user has five posts, you are initializing facebox five times. Move the script tags out of the partial. Instead, place them in show.html.erb so that they will only execute once for the entire page.

I think facebox groups the images automatically because the all have the same "rel" attribute.
Try something like this:
<%= link_to post.image_url, :rel => "facebox-#{post.id}" do %>
<%= image_tag post.image_url(:thumb).to_s %>
<% end %>

If you're still not lucky, try to remove the rel attribute and call facebox based on a class name:
<%= link_to post.image_url, :class => "facebox" do %>
<%= image_tag post.image_url(:thumb).to_s %>
<% end %>
And the javascript:
$('a.facebox').facebox()

Related

Encountered a syntax error while rendering template: check <% content_for :show do %> <div class="container"> <h1 style="color: aliceblue">

i am new to RoR and still learning, can anyone explain me how and where to use the <%= yield :whatever %> in the layouts/application.html.erb,
i tried yield with index.html.erb by using <% content_for :header do %> and placed <%= yield :header %> in the layouts/application.html.erb
and it was working perfectly fine.
now when i try it with show.html.erb by using <% content_for :show do %> and placed <%= yield :show %> in the layouts/application.html.erb, its still working fine, but when i try to add other elements using <ul>, <li>, <% %>, <%= %>, it shows me the error
Encountered a syntax error while rendering template: check
<% content_for :show do %>
<div class="container">
<h1 style="color: aliceblue">
<%= #instrument.title %>...............
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Flinger</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<div class="conatiner-fluid" style="
background: #1f4037; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #99f2c8, #1f4037); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #99f2c8, #1f4037);">
<%= render 'layouts/nav'%>
<%= yield :header %>
<%= yield :show%>
</div>
<div class="container">
<%= yield %>
</div>
</body>
</html>
index.html.erb
<% content_for :header do %>
<div class="container">
<h1 style="color: aliceblue">
Browse the latest instruments on Flinger
</h1>
</div>
<% end %>
<div class="container">
<div class="card" style="width: fit-content;">
<% #instruments.each do |instrument| %>
<%= link_to image_tag(instrument.image_url(:thumb)), instrument, class: "card-img-top" %>
<% if instrument.condition? %>
<p class="list-group list-group-flush"><%= instrument.condition %></p>
<% end %>
<h3 class="list-group-item"><%= link_to instrument.title, instrument %></h3>
<p class="list-group-item">Sold by <%= instrument.user.name %></p>
<p class="list-group-item"><%= number_to_currency(instrument.price) %></p>
<% if instrument_author(instrument) %>
<%= link_to 'Edit', edit_instrument_path(instrument), class:"btn btn-info ediit-butt" %>
<%= link_to 'Delete', instrument, method: :delete, class:"btn btn-danger deel-butt" %>
<% end %>
<% end %>
</div>
</div>
show.html.erb
<% content_for :show do %>
<div class="container">
<h1 style="color: aliceblue">
<%= #instrument.title %>
</h1>
</div>
<% end %>
<div class="conatainer">
<% #instruments.each do | instrument | %>
<ul>
<%= if instrument.brand? %>
<li><%= instrument.brand %></li>
<% end %>
<%= if instrument.model %>
<li><%= instrument.model %></li>
<% end %>
<%= if instrument.condition %>
<li><%= instrument.condition %></li>
<% end %>
<%= if instrument.finish %>
<li><%= instrument.finish %></li>
<% end %>
</ul>
<% end %>
</div>
UPDATE: it was my mistake that i used <%= %> for if condition instead of <% %> and also in my instruments_controller.rb , there was a global variable #instruments = Instrument.all.order("created_at desc") in the index method, but whereas in show method, there wasn't anything, so the problem was i used the same global variable of index method in the show.html.erb whereas i had a different variable to use for all view files

how do I link a layout to a view page on Ruby on Rails

I'm new on Ruby on Rails, it's my first time with MVC structure, and I need some help, how do I link a layout to a view page? I was looking through some tutorial but it looks so complicated and I'm so confused.
here is my view code:
<div class="container" id="login">
<div class="row">
<div class="span3"></div>
<div class="span9">
<% resource.remember_me = true %>
<%= form_for(resource, :as => resource_name, :url => session_path(resource_name), html:{role:"form", class:"form-horizontal" ,id:"form-login"}) do |f| %>
<div style="text-align: center; margin: 20px 0 20px 60px; width: 480px">
<%=image_tag 'logo_ras.gif' %>
</div>
<%= devise_error_messages! %>
<div class="control-group">
<%= f.label :email, {class:"control-label"} %>
<div class="controls">
<%= f.email_field :email, :autofocus => true %>
</div>
</div>
<div class="control-group">
<%= f.label :password, {class:"control-label"} %>
<div class="controls">
<%= f.password_field :password %>
</div>
<%=link_to "¿Olvidaste tu password?", new_user_password_path, {class: "controls"} %>
</div>
<%- if devise_mapping.rememberable? -%>
<div class="check-box">
<label><div class="controls"><%= f.check_box :remember_me %> No cerrar sesion </div></label>
</div>
<% end -%>
<div class="controls"><%= f.submit "Entrar", class:"btn btn-success" %></div>
<div style="text-align: center; margin: 20px 0 0 60px; width: 480px">
<%=link_to image_tag('banner.png'), "http://www.canalcolon.com", :target => "_blank" %>
<div>
Realización: Gestió, Organització i Comunicació, S.A.<br/>
<%=link_to "Aviso legal", legal_path %>
</div>
</div>
<% end %>
</div>
</div>
</div>
There is a layout(header) appearing in my view and I want to remove that layout, but I dont see where in the controllers I can do that. Here is my layout that is appearing in my view:
<!DOCTYPE html>
<html>
<head>
<title>NK-RAS Personalizar es futuro</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= favicon_link_tag "favicon.png" %>
<%= favicon_link_tag "favicon_57_57.png", rel: "apple-touch-icon", sizes: "57x57" %>
<%= favicon_link_tag "favicon_72_72.png", rel: "apple-touch-icon", sizes: "72x72" %>
<%= favicon_link_tag "favicon_114_114.png", rel: "apple-touch-icon", sizes: "114x114" %>
<%= csrf_meta_tags %>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<%= render 'layouts/cookies' %>
<%if Rails.env=='production'%>
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-46656081-1', ('https:' == document.location.protocol ? 'https://' : 'http://')+'www.ras-amgen.com');
ga('send', 'pageview');
</script>
<%end%>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="navbar navbar-fixed-top navbar-default" role="navigation">
<div class="navbar-inner">
<!--BUTTON BAR RESPONSIVE-->
<% if user_signed_in? and current_user.hospitals.count > 0 %>
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<% end %>
<!--APP NAME-->
<!--a class="brand" href="#">DeterminaRAS</a-->
<%=link_to(root_path) do%>
<%=image_tag("logo_ras_interior.gif",class:"brand")%>
<%end%>
<% if user_signed_in? and current_user.hospitals.count > 0 %>
<!--MENU OPTIONS-->
<div class="collapse nav-collapse">
<!-- <div class="nav navbar-nav navbar-left"> -->
<ul class="nav navbar-left">
<% if mobile_request? %>
<li><%= link_to("Determinaciones",determinaciones_path)%> <%#if can?(:index_det, Determinacion.new(medico_id: current_user.medico_id))%></li>
<li><%= link_to "Estadísticas",estadisticas_index_path %></li>
<li><%= link_to "Solicitudes",solicitudes_path if can?(:index_sol,Solicitud)%></li>
<% if can?(:crud, Hospital) && can?(:crud, Medico) %>
<li><%= link_to "Hospitales/médicos",solicitantes_hospitals_path %></li>
<% end %>
<% else %>
<li><%= link_to "Solicitudes",solicitudes_path if can?(:index_sol,Solicitud)%></li>
<% if can?(:crud, Hospital) && can?(:crud, Medico) %>
<li><%= link_to "Hospitales/médicos",solicitantes_hospitals_path %></li>
<%end%>
<li><%= link_to("Determinaciones",determinaciones_path) %> <%#if can?(:index_det, Determinacion.new(medico_id: current_user.medico_id)) %> </li>
<li><%= link_to "Estadísticas",estadisticas_index_path %></li>
<% end %>
</ul>
<ul class="nav navbar-right pull-right">
<li><%= link_to "Ayuda","/ayuda/menu.htm" %></li>
<li><%=link_to "#{current_user.whoami?}", perfil_path%></span></li>
<li><%= link_to "Salir", destroy_user_session_path, method: :delete %></li>
</ul>
</div>
<% end %>
</div>
</div>
</div>
<!-- <div id="container">
<% flash.each do |name, msg| %>
<%= content_tag :div, msg, id: "flash_#{name}" %>
<% end %>
</div>
-->
<div class="container-fluid" id="main-container">
<% flash.each do |name, msg| %>
<div class="alert alert-<%= name == :notice ? "success" : "error" %>">
<a class="close" data-dismiss="alert">x</a>
<%= msg %>
</div>
<% end %>
<%if user_signed_in? && mobile_request? %>
<div>
<%= yield %>
</div>
<% elsif user_signed_in? %>
<div id="signed_in">
<%= yield %>
</div>
<% else %>
<%= yield %>
<%end%>
</div>
<script type="text/javascript" src="https://eu-aa.appature.com/aa/12582914/script"></script>
<script type="text/javascript">aatracker.track();</script>
</body>
</html>
And here is the main controller (application controller):
class ApplicationController < ActionController::Base
protect_from_forgery
check_authorization :unless => :devise_controller?
before_filter :audit
helper_method :mobile_request?
def audit
audit = Audit.new
audit.controller = params[:controller]
audit.action = params[:action]
audit.url = self.env["REQUEST_URI"]
audit.ip = self.env["REMOTE_ADDR"]
audit.user_id = current_user.id if current_user
audit.save!
end
DEFAULT_MOBILE_AGENTS = %w(
palm
blackberry
nokia
phone
midp
mobi
symbian
chtml
ericsson
minimo
audiovox
motorola
samsung
telit
upg1
windows\ ce
ucweb
astel
plucker
x320
x240
j2me
sgh
portable
sprint
docomo
kddi
softbank
android
mmp
pdxgw
netfront
xiino
vodafone
portalmmm
sagem
mot-
sie-
ipod
up.b
webos
amoi
novarra
cdm
alcatel
pocket
ipad
iphone
mobileexplorer
mobile
maemo
fennec
silk
playbook
)
def mobile_agents
#mobile_agents ||= Regexp.union(DEFAULT_MOBILE_AGENTS)
end
def mobile_request?
(!(request.user_agent.to_s.downcase =~ mobile_agents).nil?) ||
(params[:mobile])
end
end
There are many ways layout can be used. If you want to call a specific layout for a given action, you should do that in your controller, not in your view. If you need to call in a view, to give a layout for a partial, then the syntax is different, you call the partial first and then the layout.
<%= render partial: "comments", layout: "two_column_landing" %>
If you just want your 2 column view to render in a particular controller then at the top of the controller before any method definitions call, under the class name
class ArticlesController < ApplicationController
layout "two_column_landing"
end
If you want to only call this layout for a specific action in the controller you can do it in the method render
def index
#people = Person.all
render layout: "multi-column"
end
You may refer to this question here for more details.
If you want to remove layout from all action in a controller, add layout false after the class name.
class ArticlesController < ApplicationController
layout false
end
or if you can also specify for each action
def login
...
render layout: false
end
Link to documentation

Your AdSense application status: Insufficient content

After posting my adsense code onto my Ruby on Rails app I received this message:
Insufficient content: To be approved for AdSense and show relevant ads on your site, your pages need to have enough text on them for our specialists to review and for our crawler to be able to determine what your pages are about.
The message also included these suggestions (which I think I meet with the possible exception of the 1st one and that's because it's an app not a blog):
Your content should contain complete sentences and paragraphs, not only headlines.
Ensure that your website is fully built and launched before you apply for AdSense - do not apply while your site’s still in a beta or
“under construction” phase or only consists of a website template.
Place the ad code on a live page of your website. It does not have to be the main page, but test pages that are empty except for the
AdSense ad code will not be approved.
Provide a clear navigation system for your visitors so that they can easily find all of the sections and pages of your website.
application.html.erb
<body>
<%= render 'layouts/header' %>
<div class="jumbotron">
<p class="text-center">
<%= yield :jumbotron %> <!-- this variable should be assigned in your controller action-->
</p>
</div>
<% flash.each do |name, msg| %>
<%= content_tag(:div, msg, class: "alert alert-info") %>
<% end %>
<div class="container-fluid">
<div class="container">
<div class="col-md-9">
<%= yield %> # includes pages/home (root route)
</div>
<div class="col-md-3">
<% if current_user.present? %>
<%= render 'layouts/sidebar' %> # includes _recommendations
<% end %>
</div>
</div>
</div>
</body>
_recommendations.html.erb
<div class="recommendations-padding">
<div class="ad">
<p>This is a test to see how the ads will fit here. This is a test to see how the ads will fit here. This is a test to see how the ads will fit here. This is a test to see how the ads will fit here. This is a test to see how the ads will fit here. This is a test to see how the ads will fit here. This is a test to see how the ads will fit here. This is a test to see how the ads will fit here.</p>
</div>
<div class="ad">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Recommendation 1 -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-2458646218429910"
data-ad-slot="6447006986"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<div class="ad">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Recommendation #2 -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-2458646218429910"
data-ad-slot="3293344589"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<div class="ad">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Recommendation 3 -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-2458646218429910"
data-ad-slot="9400473387"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</div>
home.html.erb
<% if logged_in? %>
<% if #user.habits.committed_for_today.any? %>
<div class="page-header">
<%= link_to habits_path(#habits) do %>
<h1><b>Habits</b></h1>
<% end %>
</div>
<div class="add-padding">
<%= render partial: 'habits', locals: {habits: #habits} %>
</div>
<% end %>
<% if #user.valuations.any? %>
<div class="page-header">
<%= link_to valuations_path(#valuations) do %>
<h1><b>Values</b></h1>
<% end %>
</div>
<div class="add-padding">
<%= render #valuations %>
</div>
<% end %>
<% if #user.goals.any? %>
<div class="page-header">
<%= link_to goals_path(#goals) do %>
<h1><b>Goals</b></h1>
<% end %>
</div>
<% end %>
<div class="add-padding">
<% if #user.goals.unaccomplished.any? %>
<%= render #unaccomplished_goals %>
<% end %>
<% if #user.goals.accomplished.any? %>
<div class="gold-standard">
<%= render #accomplished_goals %>
</div>
<% end %>
</div>
<% if #user.quantifieds.any? %>
<div class="page-header">
<%= link_to quantifieds_path(#quantifieds) do %>
<h1><b>Stats</b></h1>
<% end %>
</div>
<% end %>
<div class="add-padding">
<% if #user.quantifieds.averaged.any? %>
<h2><b>Averaged</b></h2>
<%= render #averaged_quantifieds %>
<% end %>
<% if #user.quantifieds.instance.any? %>
<h2><b>Instance</b></h2>
<%= render #instance_quantifieds %>
<% end %>
</div>
Do you have any suggestions on how I can get approved about Adsense?
Thank you!
I got approved to put up google ads via my blog. Once I got approved by google there they let you put ads on any site you own. Score!

link_to tag not including all divs

I currently have a link to tag which should wrap around all the content within it, but currently it's not doing that. It's wrapping around the code until it hits another div with a rails query inside it?
index.html.erb
<% #posts.each do |post| %>
<div class="widget" >
<%= link_to post do %>
<div class="image b-lazy" data-src="<%= post.image %>">
</div>
<div class="caption">
<h4><%= post.title %></h4>
<p>by <%= post.affiliate %></p>
</div>
<!-- LINK TO TAG ENDS HERE FOR SOME REASON -->
<div class="caption-top">
<% post.categories.each do |category| %>
<%= link_to category_path(category) do %>
<div class="tag <%= category.name %>"><%= category.name %></div>
<% end %>
<% end %>
</div>
<% end %>
</div>
Any help is appreciated!
Jonathan
Two things:
You are using link_to inside another call to link_to. That is probably not what you want.
The result of a block will be what you return from a block, normally the last line. Take a look at this question for a solution.

Partial with multiple yields in rails

I'm looking for solution to have partial with multiple yields.
In real example I have this views structure:
Basic application.erb (/views/layouts/application.erb):
<!DOCTYPE html>
<head>
<title>Some title</title>
</head>
<body>
<div class="page">
<%= yield %>
</div>
</body>
</html>
Some partial to DRY my code (/views/shared/content.erb):
<div class="content">
<div class="sidebar">
<%= yield :sidebar %>
</div>
<div class="main">
<%= yield %>
</div>
</div>
And controller view (/views/home/index.erb):
<%= render :partial => 'layouts/header' %>
<%= render :partial => 'shared/navigation' %>
<% # It is close to what I want to do %>
<%= render :layout => 'shared/content' do %>
<% content_for :sidebar do %>
<%# This is will go to application.erb, not in content.erb %>
<%= render :partial => 'shared/menu' %>
<% end %>
<%= yield %>
<% end %>
<%= render :partial => 'layouts/footer' %>
So the main issue here is to have a template block with multiple yield areas and ability to pass custom html or render another partial.
This question is old, however, it's still relevant when I was searching for an answer on Google.
I've come up with a solution, while still not beautiful, works very well. The idea uses Rails' capture method, which takes a block and stores its contents into a variable:
controller.html.erb
<%= render 'shared/partial', body: capture { %>
My body content
<% }, footer: capture { %>
My footer content
<% } %>
shared/_partial.html.erb
<div id="body"><%= body %></div>
<div id="footer"><%= footer %></div>
Hope this helps someone!
In my case I've found solution like this.
On my controller view (/views/home/index.erb):
<% sidebar_content = render :partial => 'shared/slider' %>
<%= render :layout => 'shared/content', :locals => {:sidebar => sidebar_content} do %>
<%= yield %>
<% end %>
The partial with multiple areas (/views/shared/content.erb):
<div class="content">
<div class="sidebar">
<%= sidebar %>
</div>
<div class="main">
<%= yield %>
</div>
</div>
This solution doesn't look pretty, but it works. I hope to find something better in near future.
Here is my solution:
/views/shared/_content.erb
<div class="content">
<div class="sidebar">
<%= yield :sidebar %>
</div>
<div class="main">
<%= yield %>
</div>
</div>
views/home/index.erb
<%= my_content_tag do %>
<% content_for :sidebar do %>
<%= render :partial => 'shared/menu' %>
<% end %>
<%= yield %>
<% end %>
app/helpers/my_tags_helper.rb
module MyTagsHelper
def my_content_tag(&block)
sidebar_backup = #view_flow.content.delete(:sidebar)
x = capture(&block)
html = render('shared/content') { x }
#view_flow.content[:sidebar] = sidebar_backup if sidebar_backup
html
end
end
The key is using capture to extract content_for block and pass it into #view_flow

Resources