I'm trying to set up a simple atom feed from my Posts model and I'm running into translation problems between rails 2 and rails 3.
I tried to accomplish this task with two steps:
Added the <%= auto_discovery_link_tag(:atom) %> to my /views/layouts/application.html.erb file.
Created a /views/posts/index.atom.builder file. The file contains:
atom_feed do |feed|
feed.title("Daily Deal")
feed.updated(#posts.first.created_at)
#posts.each do |post|
feed.entry(post) do |entry|
entry.title(post.title)
entry.content(post.body, :type => 'html')
entry.author { |author| author.name("Justin Zollars")}
end
end
end
I see the RSS link in my browser, but the link opens with an error:
Too many redirects occurred trying to open
“feed:http://localhost:3000/posts”.
This might occur if you open a page
that is redirected to open another
page which then is redirected to open
the original page.
Where have I gone wrong?
Try specifying a path to the feed:
<%= auto_discovery_link_tag(:atom, posts_path(:atom)) %>
Maybe you need to specify the actual feed address?
auto_discovery_link_tag :atom, "http://mysite.com/posts.atom"
If you're using FeedBurner, you'll want to use that address instead.
Also, do you have some kind of before_filter blocking the access to that page?
Related
The main table in my backend gets populated by a CSV file. When seeding and running rails db:seed , the CSV files in lib/assets/csv is read with file = File.read(Rails.root.join('lib', 'assets', 'csv', 'data.csv'), and the logic in seeds.rb runs through each row to create a table entry, populating the fields with the CSV column data.
I've also implemented Thoughtbot's Administrate for a UI admin dashboard to view this data.
So my question is, what is the best way to configure some kind of custom file upload system on Administrate dashboard if I ever need to replace the files sitting in lib/assets/csv and reseed?
I've looked at ActiveStorage but I've only ever used it to store files like an image specifically related to a table entry, not for seeding the entire table.
Yes, it is possible, and you don't need ActiveStorage. Rails's basic file upload facilities will be enough. Meanwhile, Administrate tries to follow Rails conventions, and provides hooks for you to alter the templates and refer to your own controllers and actions where you can implement this. Here's an example of how you could solve your problem.
First, you'll want to add a form with a file field. Admins will be able to use it to upload CSVs.
There are many places where you could put this form. For this example, let's say that it's "products" that you want to import (model Product), and you want to put the link in the index page.
You can override Administrate's own templates with your own ones. The following command will generate a copy of the index template that you can customize and Administrate will use instead of its own:
$ ./bin/rails g administrate:views:index
This will get you a new file app/views/admin/application/index.html.erb.
Alter it to add a link to a separate page that will host the upload form:
<% if page.resource_name == "product" %>
<div class="link-to-upload"><%= link_to "CSV Import", upload_admin_products_path %></div>
<% end %>
You can put this in between the page title and the search bar. Or wherever you want, really. It does the following:
The if checks that we are in the index page for "products" and not for something else.
The link_to links to a page that we haven't created yet, which will host the upload form.
If you load the products index page now, it will show an error NameError, with message undefined local variable or method 'upload_admin_products_path'. This is because we still don't have a route for this new page of ours. Lets add it now.
In the routes file config/routes.rb, you'll already have a route resources :products. Change it to look like this:
resources :products do
collection do
get :upload, action: 'upload_form'
post :upload, action: 'upload_process'
end
end
This actually adds two routes, not one. One will be for the form page, while the other one will be for the action that will process the uploaded CSV.
For now, you can click on the link and go to the new page. It will break again. This time the error will be Unknown action - The action 'upload_form' could not be found for Admin::ProductsController. That's because we haven't provided a view for this page yet. Let's do it now.
Add a view with the following contents at app/views/admin/products/upload_form.html.erb:
<header class="main-content__header" role="banner">
<h1 class="main-content__page-title" id="page-title">
Import products from CSV
</h1>
</header>
<section class="main-content__body main-content__body">
<%= form_for :products, html: { class: "form" } do |f| %>
<p><%= f.file_field(:file) %></p>
<p><%= f.submit "Upload" %></p>
<% end %>
</section>
Now you should be able to load the page and see the form. I have added additional markup (like those header and section elements) to make it look similar to other pages that Administrate provides.
That form has a file_field and a submit button. On submit, it will send the file to the current URL (/admin/products/upload) as a POST request. It will be handled by the post route we added earlier, on the action upload_process. Let's write that now.
On the controller Admin::ProductsController, add the following method to implement the action:
def upload_process
file = params[:products][:file]
data = CSV.parse(file.to_io, headers: true, encoding: 'utf8')
# Start code to handle CSV data
ActiveRecord::Base.transaction do
data.each do |row|
Product.create(row.to_h)
end
end
# End code to handle CSV data
redirect_to admin_products_url
end
This will create new products based on what's contained in the CSV, and then will redirect the user back to the products index page.
This example action is very simple and may not suit your needs exactly. You probably want to copy your code from seeds.rb and paste it in between my Start and End comments, so that it does what you want exactly. There are many possibilities.
I have a portfolio application built with Ruby 2.3.0 and Rails 5.0.0 that has links to external urls that work locally but do not work when deployed to Heroku.
<%= link_to image_tag(project.index_image), project.url %>
There are two different types of links that are not working and producing different symptoms.
External Application Links
In production the links to my other applications successfully redirect to the desired urls but the url's do not update in the browser to the new page.
Github links
The links to github do not work and redirect to a blank screen. That screen displays the following error in the developer console:
Refused to display 'https://github.com/my_repo' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'none'".
Try to creating a helper class for custom URL like below
On the helpers/application_helper.rb
def custom_link(image, url)
link_to image_tag(image), "#{url}"
end
And the view look like this
<%= custom_link project.index_image, project.url %>
This should work I hope because it's working my own.
Hope it helps
You can try the following:
<%= link_to project.url do %>
image_tag(project.index_image)
<% end %>
I have extensively researched this matter both on Stack Overflow and Google but found nothing conclusive. Since I'm completely new to the concept of API usage within Rails I have to ask for some advice.
I have followed the procedure from the github page
I have included the Unsplash helper in application_helper.rb as follows
def show_photo
Unsplash::Photo.find("tAKXap853rY")
end
and simply added
<%= image_tag show_photo %>
in my view.
This returns an object (So connectivity is good)
<img src="/images/#<Unsplash::Photo:0x007fc4b2f953c0>" alt="#
<unsplash::photo:0x007fc4b2f953c0>">
I'm aware that Rails is looking for a picture in the assets/images folder
How do I parse the inbound JSON and render it in my Rails view?
You can access to the urls key within the OpenStruct attributes in the Photo object that includes the raw, full, regular, small and thumb sizes, also as keys.
So, just to test you could use the raw one, like:
<%= image_tag Unsplash::Photo.find('tAKXap853rY')[:urls][:raw] %>
Or I think you could modify your method to accept one parameter which is the size key of the image, like:
module ApplicationHelper
def show_photo(size)
Unsplash::Photo.find("tAKXap853rY")[:urls][size.to_sym]
end
end
Then:
<%= show_photo('raw') %> # 'full', 'regular', etc ...
further to this solution I am trying to display the photographer's name by using the user.name method.
In the console I can get the following :
photo = Unsplash::Photo.find("tAKXap853rY")
photo.user.name
will return
=> "Alejandro Escamilla".
But in RAILS :
def show_photo(size)
#photo =Unsplash::Photo.find("tAKXap853rY")[:urls][size.to_sym]
end
just trying to display the name in my view like:
<%= #photo.user.name %> will return "user undefined method".
The .user.name is accessible in the console but not in rails! What have I missed? Thanks
I ask myself the question does an pdf tag exist in rails 4 which can show
an pdf file very simple?
This solution answers me that i need to give the correct route informations:
<%= link_to 'Help', public_path%>
I already have an pdf file in my project directory app/assets/public/help.pdf
and now i wanna have a link with the simple name "Help" to have on my page.
Third edit:
After a nice first answer nothing changes and i get the same error message from rails. What i have to write in the routes.rb if i wanna use a link for my pdf file. Does anyone know how can i link an PDF from my own directory!?
In my experience with Rails, I've never seen a PDF link tag helper.
What you want, is to use asset_path in combination with link_to
<%= link_to 'Help', asset_path('data/help.pdf') %>
#=> Help
If it needs to be absolute, you could always use asset_url
<%= link_to 'Help', asset_url('data/help.pdf') %>
#=> Help
What I usually do for linking a document that can be public is I put the document in the public folder in rails and then use this for the path:
link_to 'Help', root_path << 'TheTitleOfYourPDF.pdf'
I'm a Ruby user, trying to make a web service that receives user's active request. I made a button, of which class is a "btn-send-alert". Then after the html code, I put a script function.
<div class="page-title">
<button class="btn-send-alert" style="background-color: transparent;">Help Request</button>
<p>Hello</p><br>
</div>
........
<script>
$(".btn-send-alert").click(function(){
alert('hello!');
<% Smalier.class_alert(#lesson,current_user).deliver_now %>
});
</script>
The problem is, the ruby code just start on its own even before I click this button.
And if I click this button, no email is delivered any longer.
Maybe in some point, I think I'm seriously wrong but I can't find where it is. Is there way that I can make this function work correctly?
Looking forward to seeing the response!
Best
Thanks to Rich, I am now able to write a code that works fine! The below code is that code.
<%= content_tag :div, class: "page-title" do %>
<%= button_to "Help Request", support_path, method: :get, remote: true, class:"btn btn-danger", params: { lesson_id: #lesson.id, user_id: current_user.id} %>
<%= content_tag :i, "wow!" %>
////
def support
#lesson = Lesson.find_by(:id => params[:lesson_id])
current_user = User.find_by(:id => params[:user_id])
mailer.class_alert(#lesson,current_user).deliver_now
end
Above code runs well!
I'm a Ruby user
Welcome to Rails!!
Stateless
Firstly, you need to understand that Rails applications - by virtue of running through HTTP - are stateless, meaning that "state" such as User or Account have to be re-established with each new action.
In short, this means that invoking actions/commands on your system have to be done through ajax or another form of server-connectivity.
Many native developers (native apps are stateful) don't understand how Rails / web apps are able to retain "state", and thus make a bunch of mistakes with their code.
receives user's active request
Even if you understand how to set up authentication inside a Rails app, it's important to understand the virtues of it being stateless... EG the above line means you have to have a user signed in and authenticated before you can send the request.
This forms one part of your problem (I'll explain in a second)
ERB
Secondly, the other problem you have is with the ERB nature of Rails.
the ruby code just start on its own even before I click this button.
This happens because you're including pure Ruby code in your front-end scripts. This means that whenever these scripts are loaded (triggered), they will fire.
The bottom line here is you need to put this script on your server. Otherwise it will just run...
Fixes
1. ERB
<%= content_tag :div, class: "page-title" do %>
<%= button_tag "Help Request", class:"btn-send-alert" %>
<%= content_tag :p, "Hello %>
<% end %>
You'll thank me in 1+ months.
Convention over Configuration means you use as many of the Rails helpers as you can. You don't need to go stupid with it, but the more "conventional" your code is, the better it will be for future developers to improve it.
Another tip - only use HTML for formatting; CSS for styling. Don't use <br> unless you actually want to break a line.
Another tip - never use inline styling - Rails has an adequate asset pipeline into which you should put all your CSS
--
2. Ajax
Secondly, your use of Javascript is incorrect.
More specifically, you're calling a server-based function inside front-end views. To explain this a little more, I'll show you the famed MVC image I post on here a lot:
This is how Rails works (MVC - Model View Controller) - this means that whenever you deal with your application, you have to accommodate a layer of abstraction between the user & your app -- the browser.
By its nature, the browser is not stateful - it stores session cookies which you have to authenticate on the server. You cannot call "server" code in the front-end HTML/JS.
This is why your Ruby code is firing without any interaction, although I'm not sure how it's able to fire in the asset pipeline.
If you want to make it work properly, you'll need to create a controller action to invoke the mailer send function, which you'll be able to do using the following setup:
#config/routes.rb
get :support, to: "application#support", as: :support -> url.com/support
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
respond_to :js, only: :support
def support
Smalier.class_alert(#lesson.current_user).deliver_now
end
end
#app/views/controller/view.html.erb
<%= content_tag :div, class: "page-title" do %>
<%= button_to "Help Request", support_path, method: :get, class:"btn-send-alert" %>
<%= content_tag :p, "Hello" %>
<% end %>
#app/views/application/support.js.erb
alert ("Hello");
Each and every ruby code snippet embedded in ERB runs on server, in order to assemble a valid HTML or Javascript script for browsers to render.
Browsers don't understand ruby script at all, all they can understand is HTML and Javascript.
In your case (I'm supposing you're using rails since you tagged your question with ruby-on-rails), emails are delivered when rails engine is assembling HTML's.
If you want the emails being sent after the users click that button, the correct way is:
Define an action method in some controller, give it an URL (i.e. add a route in config/routes.rb), send email in that action.
When the button on the page is clicked, send an AJAX request to that URL.