I'm trying to get information from newsapi. I've used the basic structure i found elsewhere for another api to start with but i'm very new to this and not sure what is wrong/how to fix etc. all i'm trying to do is display the titles of the articles on my index page. At the moment, everything displays on the page, like title, author etc as an array but i just want to narrow things down and the syntax for doing so in the view. i've changed my api key to '?' for the time being(i know it should be in the .env file).ive looked at a lot of docs but i cant seem to find an answer. apologies if
this is a broad question.
class TestsController < ApplicationController
require "open-uri"
def index
url = 'https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=????????????????????????'
article_serialized = open(url).read
#articles = JSON.parse(article_serialized)
end
end
<% #articles.each do |article| %>
<%= article[1] %>
<% end %>
This should do it
<% #articles["articles"].each do |article| %>
<%= article["title"] %>
<% end %>
Edit : This is what my ruby script looks like that I used for testing
require 'json'
file = File.read 'output.json'
data = JSON.parse(file)
data["articles"].each do |item|
print item["title"]
end
I am trying to save a model named 'customer' using form_for tag. I do not have a controller for this model, i was hoping to use another controller 'public' for this task. So here is my view:
<%= form_for #customer do |f| %>
<div class="field">
<%= f.label :name %><br/>
<%= f.text_field :name %>
</div>
.... and then
<%= f.submit 'Order', :action => :save_order %><br/>
and here is my controller
def check_out
#customer = Customer.new
end
def save_order
#customer = Customer.new(params[:customer])
credit_card_no = #customer.credit_card
#order = Order.new
#order.line_items << #cart.items
#customer.orders << #order
if #customer.save
# process credit card
#cart = nil
redirect_to(:action => :show_bill, :id => #order.id)
else
flash[:notice] = 'Could not process your credit card information'
render(:action => :check_out)
end
end
The view is loaded from action 'check_out' and it was supposed to go to action 'save_order' but i am getting an error in view for 'form_for' code, what am i doing wrong ? But if i create a controller or scaffold for 'customer' and try to use that, i get redirected to 'customer/show/:id' path, and i dont want that.
If you want to use different controller with form_for you need to use :url option in form_for.
<%= form_for #customer, :url => { :controller => "your controller name",
:action => "save_order" } do |f| %>
#your code
<% end %>
Sorry, but you are asking for help in how to make something work while doing it wrong. I will try to explain and I hope this will help you.
If you want to save a customer model you should use, guess what, a customers controller. Some people like to use scaffolds, some people hate them. But the fact that the scaffold code redirects to the show method after saving a model, which is easily changed, shouldn't stop you from using it. The scaffold is just there to help beginners and/or to have a way to come up with something quick and dirty. Changing the scaffold generated code here and there is not only usually necessary it's a good way to learn.
To save an order you should use, ::drumroll::, an orders controller. I don't even know what a "public" controller would do (which by itself should tell you at least that it is poorly named).
I suggest you get the Agile Web Development with Rails book and go through the depot application. It covers all of this very subject well and you will learn a lot.
I am currently following the Ruby on Rails Tutorial by Michael Hartl. And there is something that has been bugging me for quite some time. I looked it up but I still can't find a good answer.
Anyway, I've noticed is when you have a validation error in the signup page it renders the original signup page and changes the nav bar address. I've matched /signup to the action new, but if I use render it changes from /signup to /users (the default, because of the RESTful standard I guess).
I'll leave some lines of my code:
routes.rb
resources :users
match '/signup', :to => 'users#new'
users_controller.rb
def new
#user = User.new
#title = "Sign up"
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to user_path(#user)
else
#title = "Sign up"
#user.password = ""
#user.password_confirmation = ""
render 'new'
end
end
So I've tried to work around this by not using the render method but redirect_to instead but I'm having trouble using it. As it is actually sending data to the path provided, #user.errors gets overwritten by creating a new instance of the model and the flash variable cannot show the errors.
_errors.html.erb
<% if #user.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(#user.errors.count, "error") %>
prohibited the user from being saved:
</h2>
<p>There were problems with the following fields:</p>
<ul>
<% #user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
My question is: is there any way that by using render I can change the url displayed on the navbar? It's really frustrating if someone makes a mistake in the signup form, presses enter in the navbar and ends up in a totally different place.
The reason why the address changes is because you have performed a POST request to /users/ therefore the browser is doing the correct thing by displaying the different address.
There are a few of ways around this:
Store the invalid User object and redirect back to the Users.new action.
Change the URL of the Users.create action.
Use history.replaceState to change the user's address bar.
The first option keeps the controller more RESTful, however it will need use of the :session or flash to persist the data across the redirect.
The second option keeps the code simpler, but involves fiddling with the routes.rb file.
The third option relies on javascript and support for HTML5 to mess with the user's browser history.
Personally I would leave the URL as is, but if I had a client who insisted on doing this, I would go for the second option.
I am very new to ROR and I love it so far as I develop my first app. I have a question related to my application template as I apply formatting to the nav menu.
Is it possible to check if a url path matches the root:to path set in config.rb? I have a helper method that returns the string "current" which adds the css class style to highlight the selected menu item. The helper method works fine as long as I'm not at the homepage. When I my url is www.localhost:3000/ the css current class is not applied to the Products link since the request_uri = "/" which doesn't equal "/products". I would like the css class "current" applied to the Products menu item when I'm on the homepage.
Is there any conditional logic I can use to get the root:to path and check if it matches the is_current's parameter path?
Here's my code:
routes.rb root:to setto point to the products index view
root :to => 'products#index'
application.html.erb
<%= link_to 'Products', products_path, :class => is_current(products_path) %>
<%= link_to 'Reports', reports_path , :class => is_current(reports_path) %>
application_helper.rb
def is_current(path)
if request.request_uri == path
return 'current'
end
end
Any help would be greatly appreciated.
Thanks,
bkasen
Would this work for you?
if current_page? root_path
for more info: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page%3F
If I read correctly, you want "onlink" css applied? so that when the user is on the home page, the home icon is a different color or something. If so then apply this in your header partial or where ever:
<li><%= link_to_unless_current "Home", root_path, :class => "navLinks" do link_to "Home", root_path, :class => "navLinks", :id => "onlink" end %></li>
I know this is an old question, but it may prove useful to someone else :)
Whats the proper way to set the page title in rails 3. Currently I'm doing the following:
app/views/layouts/application.html:
<head>
<title><%= render_title %></title>
<%= csrf_meta_tag %>
app/helpers/application_helper.rb:
def render_title
return #title if defined?(#title)
"Generic Page Title"
end
app/controllers/some_controller.rb:
def show
#title = "some custom page title"
end
Is there another/better way of doing the above?
you could a simple helper:
def title(page_title)
content_for :title, page_title.to_s
end
use it in your layout:
<title><%= yield(:title) %></title>
then call it from your templates:
<% title "Your custom title" %>
There's no need to create any extra function/helper. You should have a look to the documentation.
In the application layout
<% if content_for?(:title) %>
<%= content_for(:title) %>
<% else %>
<title>Default title</title>
<% end %>
In the specific layout
<% content_for :title do %>
<title>Custom title</title>
<% end %>
I found that apeacox's solution didn't work for me (in Rails 3.0.3).
Instead I did...
In application_helper.rb:
def title(page_title, options={})
content_for(:title, page_title.to_s)
return content_tag(:h1, page_title, options)
end
In the layout:
<title><%= content_for(:title) %></title>
In the view:
<% title "Page Title Only" %>
OR:
<%= title "Page Title and Heading Too" %>
Note, this also allows us to check for the presence of a title and set a default title in cases where the view hasn't specified one.
In the layout we can do something like:
<title><%= content_for?(:title) ? content_for(:title) : 'This is a default title' %></title>
This is my preferred way of doing it:
application_helper.rb
module ApplicationHelper
def title(*parts)
content_for(:title) { (parts << t(:site_name)).join(' - ') } unless parts.empty?
end
end
views/layouts/application.html.erb
<title>
<%= content_for?(:title) ? yield(:title) : t(:site_name) %>
</title>
config/locales/en.yml
en:
site_name: "My Website"
This has the nice advantage to always falling back to the site name in your locales, which can be translated on a per-language basis.
Then, on every other page (eg. on the About page) you can simply put:
views/home/about.html.erb
<% title 'About' %>
The resulting title for that page will be:
About - My Website
Simples :)
#akfalcon - I use a similar strategy, but without the helper.. I just set the default #title in the application controller and then use, <%=#title%> in my layout. If I want to override the title, I set it again in the controller action as you do. No magic involved, but it works just fine. I do the same for the meta description & keywords.
I am actually thinking about moving it to the database so an admin could change the titles,etc without having to update the Rails code. You could create a PageTitle model with content, action, and controller. Then create a helper that finds the PageTitle for the controller/action that you are currently rendering (using controller_name and action_name variables). If no match is found, then return the default.
#apeacox - is there a benefit of setting the title in the template? I would think it would be better to place it in the controller as the title relates directly to the action being called.
I prefer this:
module ApplicationHelper
def title(*page_title)
if Array(page_title).size.zero?
content_for?(:title) ? content_for(:title) : t(:site_name)
else
content_for :title, (Array(page_title) << t(:site_name)).join(' - ')
end
end
end
If title is called without arguments, it returns the current value of title or the default which in this example will be "Example".
It title is called with arguments, it sets it to the passed value.
# layouts/application.html.erb
<title><%= title %></title>
# views/index.html.erb
<% title("Home") %>
# config/locales/en.yml
en:
site_name: "Example"
You can also check this railscast. I think it will be very useful and give you basic start.
NOTE: In case you want more dynamic pages with pjax
I have a somewhat more complicated solution. I want to manage all of my titles in my locale files. I also want to include meaningful titles for show and edit pages such that the name of the resource is included in the page title. Finally, I want to include the application name in every page title e.g. Editing user Gustav - MyApp.
To accomplish this I create a helper in application_helper.rb which does most of the heavy lifting. This tries to get a name for the given action from the locale file, a name for the assigned resource if there is one and combines these with the app name.
# Attempt to build the best possible page title.
# If there is an action specific key, use that (e.g. users.index).
# If there is a name for the object, use that (in show and edit views).
# Worst case, just use the app name
def page_title
app_name = t :app_name
action = t("titles.#{controller_name}.#{action_name}", default: '')
action += " #{object_name}" if object_name.present?
action += " - " if action.present?
"#{action} #{app_name}"
end
# attempt to get a usable name from the assigned resource
# will only work on pages with singular resources (show, edit etc)
def object_name
assigns[controller_name.singularize].name rescue nil
end
You will need to add action specific texts in your locale files in the following form:
# en.yml
titles:
users:
index: 'Users'
edit: 'Editing'
And if you want to use meaningful resource names in your singular views you may need to add a couple of proxy methods, e.g.
# User.rb
def name
username
end
I thought it will be good:
<title>
<% if #title %>
<%= #title %>
<% else %>
Your title
<% end %>
</title>
And give a value to #title in your controller, or the title will be Your title
My answer is more simple:
locales/any_archive.yml:
pt-BR:
delivery_contents:
title: 'Conteúdos de Entregas'
groups:
title: 'Grupos'
And inside of application.html.slim:
title
= "App Name: #{t("#{controller_name.underscore}.title")}"
There's a simple way to manipulate layout variables (title, description, etc.):
# app/views/application.html.erb
<title>
<%= content_for :title || 'App default title' %>
</title>
# app/views/posts/index.html.erb
<%= content_for :title, 'List of posts' %>
And other pages will have App default title value for their titles
In application layout:
# app/views/layouts/application.html.erb
<title><%= (yield :title) || 'General title' %></title>
then in each view where you want a specific title:
<% content_for :title, 'Specific title' %>
There are already some good answers, but I'll add my simple approach. Add this to layouts/application.html
- if content_for?(:title)
-title = "My site | #{content_for(:title)}"
-else
-title = "My site | #{controller_name.titleize}"
You automagically get a nice names on all your views like "My site | Posts" -- or whatever the controller happens to be.
Of course, you can optionally set a title on a view by adding:
- content_for(:title, 'About')
and get a title like "My site | About".