'.each do' is leaving some line like "#<Table:0x224af70>" - ruby-on-rails

I'm trying to prepare a json object for my rails app.
Here is my code:
#videos_controller
def show
#video = Video.find(:all,
:conditions => { :published => true, :trash => false },
:order => 'RANDOM()', :limit => 1)
respond_to do |format|
format.html # show.html.erb
format.json {render :partial => "videos/show.json"}
end
end
#_show.json
<%= #video.each do |video| %>
{
"video_link": "<%= video.link %>",
"video_id": "http://website.com/videos/each/<%=video.id%>"
}
<% end %>
but at videos/show.json I'm getting something like that
{
"video_link": "http://www.youtube.com/watch?v=6rmWnwtps6I",
"video_id": "http://website.com/videos/each/51"
}
#<Video:0x220a060>
How to avoid the nasty last line and were does it getting from? I think, becouse of that, it doesn't allow me to work with json object properly. I know, that answer is pretty simple, but just can't get it. Thank you in advance.

Take out the equal sign in the line <%= #video.each do |video| %> so it's just <% #video.each do |video| %>. The segment you're seeing is the default to_s method which is being returned from the each method.

Change this:
<%= #video.each do |video| %>
to this:
<% #video.each do |video| %>
Since you’re outputting text in the body of the loop, you don’t want to output the loop itself (the result of which is the enumerable itself).

Related

Render Partial Item only if column is true

I'm trying to loop over my 'offers' collection in a partial, but each 'offer' has a column 'featured' which is a boolean which defaults to false. I'm trying to loop over the collection and only display the offers which have the featured column set to true.
I currently have:
<%= render #offers %>
Trying below but comes back with 'undefined method 'featured'
<%= render #offers if #offer.featured == true %>
Any help would be fantastic
In your controller, set up another collection:
#featured_offers = Offer.where(featured: true)
And render that instead:
<%= render #featured_offers %>
To correct your immediate code, you're calling .featured on #offer - which doesn't exist.
You'll either need to loop through #offers and use logic on offer, or use conditions inside the partial (which is highly inefficient):
<% #offers.each do |offer| %>
<%= render offer if offer.featured %>
<% end %>
or
<%= render #offers %>
#_offer.html.erb
<% if offer.featured %>
This is super inefficient
<% end %>
--
#jason is correct with his recommendation of using a where clause
You may even want to go a step further and set up a scope:
#app/models/offer.rb
class Offer < ActiveRecord::Base
scope :featured, -> { where featured: true }
end
#offers = Offer.featured
You can even chain the scope:
#offers = Offer.where(user_id: params[:id])
<%= render #offers.featured %>

Can't pass multiple locals when rendering JS

I'm trying to render a javascript file (through a remote AJAX call) using the following code:
respond_to do |format|
format.js { render "like", :locals => {:media_id => media_id, :like_type => like_type}}
end
The file is named "like.js.erb" and I know it will work because when I put just a standard javascript alert in the file, it works perfectly.
The file (like.js.erb) looks like this:
<% if like_type == "l" %>
alert("liking as <%= like_type %> for media_id <%= media_id %>");
$('like_<%= media_id %>').update("liked");
<% elsif like_type == "u" %>
alert("unliking as <%= like_type %> for media_id <%= media_id %>");
$('like_<%= media_id %>').update("unliked");
<% end %>
When the file contains the code above, the POST action completes properly but nothing is returned at all. It seems that it doesn't like the multiple locals being passed.
Any ideas? Thanks!
If you use the :locals option then you need to provide the :partial key as a parameter.
respond_to do |format|
format.js { render :partial => "like", :locals => {:media_id => media_id, :like_type => like_type}}
end
or:
respond_to do |format|
format.js { render "like", :media_id => media_id, :like_type => like_type}
end

AJAX Form Issues with Ruby on Rails

I'm sure this question has been asked before in a different context but I'm still so stuck with figuring out AJAX Rails and, I guess, Rails in general (kinda makes me wonder if I should just go back to PHP...). Well anyways I have this form that I want to AJAXify.
This is the "list" view which is part of the "subject" controller
<h1>Listing Subjects</h1>
<ul id="subject_list">
<% #subjects.each do |c| %>
<li><%= link_to c.name, :action => 'show', :id => c.id %></li>
<% end %>
</ul>
<p id="add_link"><%= link_to_function("Add a Subject",
"Element.remove('add_link'); Element.show('add_subject')")%></p>
<div id="add_subject" style="display:none;">
<%= form_tag(:action => 'create') do%>
Name: <%= text_field "subject", "name" %>
<%= submit_tag 'Add' %>
<% end %>
</div>
Code for my "subject" controller
class SubjectController < ApplicationController
def list
#subjects = User.find(:all)
end
def show
#subject = User.find(params[:id])
end
def create
#subject = User.new(params[:subject])
if #subject.save
render :partial => 'subject', :object => #subject
end
end
end
My "subject" partial
<li id="subject_<%= subject.id %>">
<%= link_to subject.name, :action => 'show', :id => subject.id %>
</li>
And the User is just a simple model I made that contains two columns "name" and "email".
How this code currently works is that when you click "Add", the textfield input is revealed. When you type something in the input and submit it, the "_show" partial is rendered in the create link. I was following a Rails 2.0 tutorial but I have 3.0 and I've read through some tutorials and they all mention ":remote => true" and jquery_ujs.js but I have no idea how to apply them to a "form_tag" rather than "form_for" Rails helper.
Basically I want to asynchronously add the element to the bottom of the list without a page load. I've really tried to understand absolutely all of the tutorials I could find but I just can't figure it out.
I believe that you'd better use some Unobtrusive JavaScript to tell to your app
and browser what exactly you want to render and how.
You want too much from simple render :partial => 'subject', :object => #subject line of code.
Here's my snippet that may be helpful to you.
# in the view (:remote => true for form_tag is not problem at all)
<%= form_tag({:controller => :products, :action => :empty_cart }, {:id => 'empty_cart', :remote => true}) do %>
<%= submit_tag 'Clear' %>
<% end %>
# in the controller (note that format.js section in the respond_to block)
def empty_cart
...
respond_to do |format|
format.html { redirect_to :root, :notice => 'Your cart is empty now' } # in the case of disabled JS support
format.js { render :js => "$('#empty_cart').fadeOut()" } # or you can place js code in the empty_cart.js.erb file and specify format.js here without the block
end
end
Check this article if I'm not clear enough.

processing controller actions as JS instead of HTML

So I have the following form:
<%= form_tag url_for(:controller => 'profile', :action => 'follow_topic'), :remote => true do %>
<%= hidden_field_tag :topic_id, topic_id %>
<%= content_tag :button, :class => 'link', :onclick => "javascript:document.getElementById('followtopic#{Topic.find(topic_id).identifier}').innerHTML='Following...'" do %> Follow <% end %>
<% end %>
and I'm trying to get the controller to process it as JS in place of HTML. The funny thing is I have a form exactly like this in another spot in the app that seems to work fine, and the controller definitions are the same. Can't quite figure out the problem. Any ideas on what I should be checking first?
def follow_topic
#topic = Topic.find(params[:topic_id])
current_user.follows << #topic
respond_to do |format|
format.js
end
end
You got it right except your format.js isn't doing anything. What are you expecting in your form submit? and what are you expecting in return? a json or http response 200?
specify that in your format.js like so:
...
respond_to do |format|
format.js { render :nothing => true, :response => :ok if current_user.follows << #topic }
end
...
or something to that effect.
This question is OLD but it's unanswered and I just struggled with the same problem for hours, so hopefully this will help someone in future.
Make sure app/assets/javascripts/application.js contains:
//= require jquery
//= require jquery_ujs
And that erb contains <%= javascript_include_tag "jquery", "jquery_ujs" %> and not just a <script> tag.
This is what fixed it for me.

Issue iterating records

I'm sure this is a stupid question, but I've got a todo list app I've built in Rails. There are projects and projects have many tasks. Aside from seeing projects with their tasks, I also wanted to see a simple listing of all of the tasks. The index action in the tasks controller looks like this:
def index
#tasks = Task.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #tasks }
end
end
And in views/tasks/index.html.erb I simply had this to start:
<%= #tasks.each do |t| %>
<%= t.title %>,
<% end %>
But when I look at /tasks, I get this:
Task 1, Task 2, Task 3
#<Task:0x103225138>#<Task:0x1031ea998>#<Task:0x1031ea858>
I can't figure out why the
#<Task:0x103225138>#<Task:0x1031ea998>#<Task:0x1031ea858>"
...are appearing or how to keep them from appearing. They appear even if I'm not printing anything other than the loop code. Any ideas? Thanks!
<% #tasks.each do |t| %>
<%= t.title %>,
<% end %>
Will fix that. The problem is that you are printing with = the result of .each which returns the array it was called on, in this case #tasks. So your code is effectively doing this:
<% #tasks.each do |t| %>
<%= t.title %>,
<% end %>
<%= #tasks %>
A side note:
A much nicer way to do this is simply
<%= #tasks.map(&:title).join ", " %>

Resources