Ruby On Rails Display Image - ruby-on-rails

I am a newbie at it.I have just educated myself for 2 days. And a have a problem.
Example: I have a table , called as tblData, includes 2 columns: id, img_link. img_link contains link to an image.
I want to show all of them in this table(id and image, not image link) into a html file.
So, exactly what I need do?

If you have an image link that you can pull from your database, you can do something like this:
Assuming you have an object assigned and everything's set up:
In your controller for tbl_data (e.g. app/controllers/tbl_data_controller.rb):
class TblDataController < ApplicationController
def your_action
#tbl_data_item = TblData.first
end
end
(The code above is just an example, you should substitute for whatever code/query you wish to run)
In your view template, you can render an image from a link using the following Rails view helper:
<%= image_tag(#tbl_data_item.img_link) %>
This would output the following HTML:
<img src="/path/to/image/from/img_link" />
There's a lot more info on this helper on the Rails api docs. The Rails Guides has some awesome info on getting things set up and running as well. Hope this helped!
UPDATE:
To give you a better example with clearer steps, you would do something like the following:
Set up your routes (app/config/routes.rb):
Rails.application.routes.draw do
resources :tbl_data
end
Create your model, used to communicate with its respective database table (app/models/tbl_data.rb):
class TblData < ActiveRecord::Base
# your model-specific code goes here - validations, scopes, etc.
end
Create the controller, which responds to when a user hits a certain route in your app (app/controllers/tbl_data_controller.rb):
class TblDataController < ApplicationController
def your_action
#tbl_data_items = TblData.all
end
end
Create the view template, that will be rendered for your user(app/views/tbl_data/your_action.rb):
<table>
<% #tbl_data_items.each do |item| %>
<tr>
<td><%= item.id %></td>
<td><%= image_tag(item.img_link) %></td>
</tr>
<% end %>
</table>
The above would show a table with each record in the #tbl_data_items as a row, with 2 columns, one with the id, and one with the actual image for that item.

Create a folder in public called images, put the desired image in that folder.
Put <%=image_tag 'whatevertheimagefilenameis.png', class: 'example-class', id: 'example-id'%> in the html.

Related

Render results on #show without storing data in ActiveStorage

I'm learning RoR by building my first app (yay!). I gotta a question thought as rails guides do not cover this topic:
How to render unique results on #show to a user without storing any data in a model?
Steps I want to take:
Create a basic index view with a form_tag that will allow user to submit a link (string) and click submit button
Write Service Objects that will allow me to parse that link and create a response I want user to see
I want to write a #show method in a separate controller that will allow me to display all the data. (I also want to parse my params[:link] in that method using Service Objects.
I want to finally display this data in a table in #show view (probably I need to create a unique #show/[:id] for each user?
Here's what my app looks like at the moment (more or less):
Static Controller (just to render index.html.erb with a form)
class StaticController < ApplicationController
def index
end
end
Static Index view (yup, parsing imgur link here)
<h1>Hello Rails!</h1>
<%= form_tag("/images", method: "post") do %>
<p>
<%= label_tag(:imgur_link) %><br>
<%= text_field_tag(:imgur) %>
</p>
<p>
<%= submit_tag("Get my cards") %>
</p>
<% end %>
Images Controller (where all the magic SHOULD happen)
class ImagesController < ApplicationController
def show
#collection = params[:imgur_link]
#service1 = service1.new(*args).call
#service2 = service2.new(*args).call
...
end
end
Images Show view
Empty as I'm stuck with the Images controller at the moment.
Any help would be more than appreciated.
Thanks!
There is no reason you should put something into storage just in order to display it. If you get to a point when you have the results in your controller, you could just pass them to view in some #variable
As I see, you have set up the form for step 1. If you also have routes.rb call 'images#show' for POST /images, then you will have params[:imgur_link] available in your show action. This should do:
# config/routes.rb
YourApplication.routes.draw do
# ...
post '/images' => 'images#show'
end
Now you have to somehow process that link. Since I don't know what your results should be, I'm going to assume that you have two classes, Service1 and Service2, both of which accept an URL and return collection of results, and both collections hold the elements of the same class. Then you can leave only unique results for your show view, like this:
# app/controllers/images_controller.rb
class ImagesController < ApplicationController
def show
link = params[:imgur_link]
results1 = Service1.new(link).results
results2 = Service2.new(link).results
#results = (results1 + results2).uniq
end
end
Then you can do something with #results in your show view. E.g.
# app/views/images/show.html.erb
<% #results.each do |result| %>
<%= result.inspect %>
<% end %>

How to call a model method from rails view through a controller?

Please bear with me. I went through similar questions here but my requirement is quiet different.
I have a model called RideLaterRequest. In the app I am allowing the user to create a record on this model. And currently once the record is saved a notification is being sent to a android app. The logic is as follows:
ride_later_request.rb
class RideLaterRequest < ActiveRecord::Base
after_save :send_notif #run send_notif method once the record is saved.
def send_notif
RideLaterRequestHandler.ride_later_request_created(self)
end
end
The above method actually calls another class method (the earlier developer defined a method in a separate class)
class RideLaterRequestHandler
def self.ride_later_request_created(ride_later_request)
#####................####
end
end
So once this method executes a notification is being sent to the android app.
Now I am trying to stop this automated system. And handle this flow manually by adding a button in view file.
First I stopped the automated notification by commenting after_save :send_notif in the ride_later_request.rb file. So now there are no notifications being sent once a new record is saved on that model.
In a view file I am displaying the records of RideLaterRequest model as follows:
admin_reports_controller.rb
class AdminReportsController < ApplicationController
def trip_report
#ride_later_request = RideLaterRequest.all
end
end
trip_report.html.erb
<table>
<tr>
<th>Date</th>
<th>Trip ID</th>
<th>Send Notification</th>
</tr>
<% #ride_later_requests.each do |trip_report| %>
<tr>
<td><%= trip_report.planned_start_time.to_date%></td>
<td><%= trip_report.id%></td>
<td>
<%= button_to "Send Notification", #In normal case I would have added a path to the controller method to Send notification here %>
</td>
</tr>
</table>
As you can see I am trying add a button action where it sends the notification. The only thing I am trying to do here is, earlier the notifications were being sent once a new ride_later_request row was created. Now I am stopping that and trying to do it manually on a already saved record by adding a button. My question is is how can I call def send_notif model method that I have explained above in the beginning on this button that I am trying to give ?
I know this is app specific question but I have tried my best to make it rails specific by explaining it, I guess. Help is much appreciated.
How about creating a send_notification action on your RideLaterRequestController and then (in routes.rb) setting up a send_nofication_ride_later_request path. Perhaps something like:
resources :ride_later_requests do
member do
post :send_nofication
end
end
Which yields:
send_nofication_ride_later_request POST /ride_later_requests/:id/send_nofication(.:format) ride_later_requests#send_nofication
POST /ride_later_requests(.:format) ride_later_requests#create
ride_later_requests GET /ride_later_requests(.:format) ride_later_requests#index
new_ride_later_request GET /ride_later_requests/new(.:format) ride_later_requests#new
edit_ride_later_request GET /ride_later_requests/:id/edit(.:format) ride_later_requests#edit
ride_later_request GET /ride_later_requests/:id(.:format) ride_later_requests#show
PATCH /ride_later_requests/:id(.:format) ride_later_requests#update
PUT /ride_later_requests/:id(.:format) ride_later_requests#update
DELETE /ride_later_requests/:id(.:format) ride_later_requests#destroy
Then do something like:
<%= link_to 'Send Notification', send_nofication_ride_later_request_path(trip_report), method: :post %>
You can dress that link to look like a button.
Then, in your RideLaterRequestController, something like:
class RideLaterRequestController < ApplicationController
...
def send_notification
#ride_later_request = RideLaterRequest.find_by(id: params[:id])
RideLaterRequestHandler.ride_later_request_created(#ride_later_request)
# redirect, render, or whatever depending on whether you want this
# to be AJAXy or regular HTML.
end
...
end

Using exists? in Rails 4

I am trying to query the DB to see if an Open House exists for a specific listing. If it does, I would like it to display a span. I created a helper based on what I read, but the span is displaying on all of the listings, not just the ones that have an upcoming open house. Any help is appreciated.
ApplicationController:
class ApplicationController < ActionController::Base
def upcoming_oh
if #open_houses = OpenHouse.exists?
end
end
helper_method :upcoming_oh
end
Listings Index:
<% upcoming_oh %><span class="label label-nklyn-yellow">Upcoming Open House</span>
You can check if your model contains a specific record using exists function
if OpenHouse.exists?(your_record)
# do stuff
end
I'm not sure what is OpenHouse, but I think it's a model of your's, anyway this logic should solve your issue
you can use if/else to display/hide a span or div or whatever you want after that like this
<% if #condition %>
<span>
<% end %>

setting a dynamic link_to rails

I'm pretty new to rails and I'd like to set my links for a certain page dynamically. I have a table called "Unfinished" and it has a column called "link" (corrected from "links") I'd like to be able to call the "link" record in the view to set my link_to link path.
I am trying to do this...
<%= link_to #unfinished.link(:p => #post.id) do %> FINISH <% end %>
...but that's not working.
my controller says:
def show
#post = Post.find(params[:id])
#unfinished = Unfinished.where('progress = ?', #post.progress).last
end
and the controller logic works fine...until I try to put the #unfinished.link into link_to
Edit:
Error Message:
wrong number of arguments (1 for 0)
Model
class Unfinished < ActiveRecord::Base
end
The type of links are :
step1_path
step2_path
step3_path
I am making a multipage form that you can save partway through. Based on a value in the #post.progress column (like 1, 2, 3) the correct path to complete the post will be provided (step1_path, step2_path etc...)
try this.
<%= link_to eval(#unfinished.link.to_s) do %> FINISH <% end %>
since the link you want is actually a named route, so you will need to eval it.
but with this you wouldn't be able to be able to pass in the post id, which you will need.
If the route is the same for all records (save for what part you are on based on the progress attribute) do you even need to store it in the database? You could just make the link method return the path (that you would still need to eval).
something like
def link (post)
"step#{self.progress}_path(post.id)"
end
and then eval the link on the way back. but Not sure if that will work, just thinking out loud...
There are gems that do multi-stage forms perhaps looking into them might help?

pass value of td element to rails controller

I'm trying to pass the value of a element to a rails controller!
Currently, I have something like this:
<td id="dbname"><%= link_to db, :action => :show %></td>
This represents a row in an html table, which contains a string value, e.g. "development".
When the user clicks on the "development" link, the <%= link_to ... %> grabs the value from the current clicked and passes that to a rails controller action, in this case the show action.
How can this be achieved!?
UPDATE - generating links:
<% #dbs.each do |db| %>
<tr>
<td id="dbname"><%= link_to db, :action => :show %> </td>
</tr>
UPDATE 2:
this is my index controller:
conn = Mongo::Connection.new
#dbs = conn.database_names #this returns an array of strings (which are the names of the databases)
Now I want to be able to click on of these databases and then to pass the clicked text to the rails controller show action. I'm not sure how I would generate a custom resources path for these links... but I was contemplating of doing it using Ajax or something javascript related. Maybe get the text of clicked link using jQuery and then send an Ajax request to the rails controller with the text as a parameter!
I think that it's a strange thing what you're trying to do, but a solution could be to use javascript to append the id to the href of each link as a query string.
If you could explain a little bit what you're trying to achieve maybe we could find a better solution.
Hope it helps!
Edit:
If you have a table of links I think that you should consider them as a resource and managing them the REST way.
Your controller should have an index and show action and you should declare the links as a resource in the routes file (maybe link it's a reserved word and you will have to use a different name, I'm not sure), the index action will fetch all the links and when you render them, you could specify the link for each one with something similar to "link_path(link.id)" (remember, you should have a show action defined) in the controller you will receive the link id so you could load it with a simple "find" and pass it to the view.
I recommend you to always look for the REST way to solve a problem in ROR.
Edit 2:
Ok let's see if this works for you:
I suppose that you have a model that represent those links that you're talkin about, for example:
class DataBaseLinks < ActiveRecord:Base
end
This model with be backed up by a table in your database, if you have generated it the rails way, you will also have an id column that identify each database link.
in your controller, let's say DataBaseLinksController, you'll have:
class DataBaseLinksController < ApplicationController
def index
#dabatase_links = DataBaseLink.all
end
def show
#database_link = DataBaseLink.find(params[:id])
end
end
(I've avoided all the validations and checks).
All you have to do in your index.html.erb is:
<% #database_links.each do |database_link| %>
<%= link_to database_link.name, database_link_path(database_link.id) %>
<% end %>
This will generate all the links with the correct path to the show action (maybe the route helper is a little bit different, but not so much).
Notice also that you'll have to add into your routes.rb the following line:
resources :database_links, :only => [:index, :show]
How do you see it?
Edit 3:
(I'll delete all my edited answers when we find a correct one)
Ok I'm going to suppose that you are not using something like mongoid so you don't have active record similar objects.
Have you tried this in your view:
<% dbs.each do |dbs_name| %>
<%= link_to dbs_name, :controller => "your_controller", :action => :show, :dbs_name => dbs_name %>
<% end %>

Resources