Passing a variable to a view in Ruby on Rails - ruby

How can I pass #films to view file films.html.erb and display it on the view file?
def index
#films = Film.select("Title, Year").order('created_at DESC');
#htmldoc = File.read(Rails.root.join('app', 'views','films.html.erb'))
respond_to do |format|
format.html { render html: #htmldoc.html_safe}
end
end

If you want to render the films.html.erb then you don't need to open and read the file, use just the template option for render within your index method.
Adapt a bit your method to something like this:
def index
#films = Film.select('Title, Year').order('created_at DESC')
render template: 'view/films'
end
Note view must match with the name of the folder where's that erb file.

Related

Check form submitted values in ruby on rails

On my rails app I have a form on /addfiles where user can add file path in text boxes and this form is submitted to /remotefiles
I have created a route match '/remotefiles' => 'main#remotefiles'
and function in main controller
def remotefiles
render layout: false
end
and add remotefiles.html.haml in views/main
how can I show these submitted values on remotefiles, I think it can be done with render but not sure how can I use it to pass form values and show them on view.
Is there a way to check form data in ruby on rails just like php print_r function ?
Your form data is coming in via the params hash. The simplest way to respond with it would be
# MainController
def remotefiles
render json: params
end
If your form contained fields named foo and bar, you'll see those as well as some parameters Rails adds:
{
"foo": 1,
"bar": 2,
"controller": "Main",
"action": "remotefiles"
}
If you want to render them into a real template, write the HTML into app/views/main/remotefiles.html.erb. Rails will by default render a template matching your controller and action, or if you want a different one you can instruct Rails to render "path/to/other/template". Your template can access params too, but the more typical way to pass data into them is by setting instance variables in the controller.
# MainController
def remotefiles
#foo = params[:foo]
#bar = params[:bar]
end
# app/views/main/remotefiles.html.erb
<strong>Foo</strong> is <%= #foo %>
<strong>Bar</strong> is <%= #bar %>
Lastly, if you don't actually want to render the form data back to the browser, just inspect it during development, Rails.logger will print it into your server log.
# MainController
def remotefiles
Rails.logger.info(params[:foo], params[:bar])
end
You should read up on how Rails works - the getting started guides are very clear and helpful. Here's the one on rendering.

Rendering partial that belongs to another controller

I've got a menu controller, which is set as my root controller in routes.rb. In my menu view, i try and render the _lights.slim partial with = render :partial => 'lights/lights' but i get the following error: undefined method `lights' for nil:NilClass
MenuController:
class MenuController < ApplicationController
def index
end
end
Menu View (index.slim)
ul.tabs.vertical data-tab=""
li.tab-title.active
a href="#panel1a" Tab 1
.tabs-content.vertical
#panel1a.content.active
= render :partial => 'lights/lights'
LightsController
class LightsController < ApplicationController
before_action :discover_lights
include LIFX
#client = LIFX::Client.lan
#client.discover!
3.times do
#client.lights.refresh
sleep (0.5)
puts "Found #{#client.lights.count} with labels #{#client.lights}"
end
def index
end
def new
end
def light_toggle
light = #client.lights.with_label(params[:label])
light.on? ? light.turn_off : light.turn_on
redirect_to '/'
end
private
def discover_lights
#client = LIFX::Client.lan
#client.discover!
end
end
Lights View (_lights.slim)
h1.subheader LIFX Lights
table.light-table
thead
tr
th Light
th Status
th Power On/Off
th Brightness
tbody
-#client.lights.map do |c|
tr
th #{c.label}
th #{c.power}
th =link_to 'Toggle', light_path(:label => c.label)
th #{c.color.brightness.round(2) * 100}%
end
Routes.rb
root 'menu#index'
get '/lights', to: 'lights#index'
get '/lights/:label', to: 'lights#light_toggle', as: 'light'
I know this is a no brainer, but i'm stuck as to what to do here. I'm thinking it must be an issue with the way that when Menu#Index is called, I never knows about my LightsController, and so #client.blablabla will never make sense. But how will I make my app know about my LightsController when the view is loaded as a partial
Partials
You must appreciate that Partials are not controller-dependent (being stored in a controllers' view directory does not tie them for use with that controller)
This means if you have the functionality to support the partial in another controller, you should be able to use it in different parts of your app
--
Error
This leads us to the identification of the problem you're receiving.
It's not the calling of the partial which causes an issue - it's how you're referring to the code inside it:
undefined method `lights' for nil:NilClass
The error is clearly that you're trying to call the lights method on an object / variable which doesn't exist. This is defined inside the partial itself here:
#client.lights.map do |c|
Therefore, you need to be able to pass the correct data to the partial, enabling it to load the #client object without being dependent on the controller
--
Fix
To do this, you may wish to consider using partial locals -
<%= render partial: "lights/lights", locals: {client: #client} %>
This means that every time you call the partial, you'll have to pass the #client object into the client local var, thus allowing the partial to run controller-independently.
Here's how you'd handle it in the partial itself:
#app/views/lights/_lights.slim
- client.lights.map do |c|

How to display contents from a sequel database connection in the view file in Ruby?

I am trying to retrieve data from a PostgreSQL database with Sequel in Sinatra.
DB = Sequel.connect('postgres://connection_data')
items = DB[:items]
Then I try to get an entry with a specific ID:
get '/:id' do
#item = items.filter(:id => params[:id])
erb :edit
end
In my edit view I would like to display the content of the #item variable. The problem is that I don´t know how to get for example the ID.
<% if #item %>
Do something
<% else %>
<p>Item not found.</p>
<% end %>
I tried using #item.id and #item[:id] but both don´t work. I get an error undefined method 'id' for #<Sequel::Postgres::Dataset:0x007fac118b7120>. What would be the right way to retrieve the values from the #item variable?
#item = items.filter(:id => params[:id]) returns a dataset. If you want a single item, you should do: #item = items.first(:id => params[:id].to_i)
Also #item.id is probably not want you want. Given that items = DB[:items], you are using a plain dataset and then #item = items.first(:id => params[:id].to_i) is going to give you a hash. You need to do #item[:id] to get the item's id.
You may want to look at using models instead:
# model file
class Item < Sequel::Model; end
# sinatra code
#item = Item[params[:id].to_i]
# template
#item.id
Actually #item.id is the right way. The only problem I can see in your code is
#item = items.filter(:id == params[:id])
which should be
#item = items.filter(:id => params[:id].to_i)
EDIT:
Try this:
#item = items.where(:id => params[:id].to_i)
#item.select(:id) #to embed
params[:id] is giving a string, so convert it to an integer.

get date from the jquery datepicker in the rails controller

I have a form where the date has to be selected and it has to be passed to an action. But it is not passing as params to that action. I am using jquery datepicker for selecting dates.
View page
<%=f.text_field :due_date%>
Controller page
def create
#task = Task.new(params[:task])
if #task.valid?
#task.due_date=params[:task][:due_date]
#task.save
redirect_to(calenders_path(:date=>#task.due_date,:task_name=>params[:task][:task_name]))
else
render :action=>"new"
end
end
Here only :task_name is passing as params
Please help
Try this:
def create
#task = Task.new(params[:task])
if #task.save
redirect_to(calenders_path(:date=>#task.due_date,:task_name=>#task.task_name))
else
render :action=>"new"
end
end
The due_date param should already be populated by the first line. You might be setting it to null with #task.due_date=params[:task][:due_date].

Include picture url to xml file

I have the following which renders information from my groups in through xml, this code works well.
respond_to do |format|
format.html # index.html.erb
format.xml {
groups_xml = #groups.to_xml(:include => [:enrolled_users, :tracks, :events])
render :xml => courses_xml
}
end
end
In a second part I want add url picture to this xml.
Currently I use the following code to get the picture url, and know I need to add it to the xml render but I don't know how
picture = Groups.find(params[:id]).groups.logo.public_filename(:avatar)
I'm looking for an answer for 1 month and now I don't know where I can find out.
Assuming that each group has a logo that you're trying to include in the xml, you could add a method to the group model like:
class Group
def avatar_filename
logo.public_filename :avatar
end
end
and then add :avatar_filename to the :include option you are already passing to to_xml, like this:
#groups.to_xml(:include => [:enrolled_users, :tracks, :events, :avatar_filename])
Is this what you're looking for?

Resources