I am trying to achieve variable variable concept of PHP in grails, my code structure is somewhat similar to,
<%
def a = 6
def b = "a"
println "${"$b"}"
%>
I would like the output of
println "${"$b"}"
6, is it possible in any way?
the data is passed from the controller in some structure like [template:"something.gsp",model:["age":5,"date":"2011-01-01","id":9, listedKey:["age","date","id"]]] now when I iterate over the list listedKey I would like to get the value of its respective variable in view
Access the model map like this:
<g:each in=${listedKey} var="key">
${binding[key]}
</g:each>
You can do the following just straight in the gsp:
<g:set var="a" value="${6}"/>
<g:set var="b" value="a"/>
${a}
"${b}"
or
<%
def a = 6
def b = "a"
out << b
%>
${b} <- also working
Related
I use raw SQL to build an SQL editor in my project. But when I call simple select queries, I get this result:
[{"id"=>1, "name"=>"Ukraine", "phone_code"=>"+38", "created_at"=>"2015-11-23 21:52:49.415748", "updated_at"=>"2015-11-23 21:52:49.415748", 0=>1, 1=>"Ukraine", 2=>"+38", 3=>"2015-11-23 21:52:49.415748", 4=>"2015-11-23 21:52:49.415748"}]
The query is simple:
SELECT * FROM countries
As you can see, the same fields are displayed firstly with titles of attributes, and then second time with integer indexes.
I use this code two output only elements with attribute titles:
#headers = #result.first.keys
#count = #headers.size / 2
After that I iterate over headers:
<tr>
<% (0...#count).each do |i| %>
<th><%= #headers[i] %></th>
<% end %>
</tr>
But I think that it is not the best solution. So, what is the best way to output only elements with proper titles, not with indexes?
Try select_all
$ bin/rails c
Loading development environment (Rails 4.2.4)
>> result = ActiveRecord::Base.connection.select_all "SELECT * FROM wingnuts"
(0.4ms) SELECT * FROM wingnuts
=> #<ActiveRecord::Result:0x007fb92fbcdb18 #columns=["id", "size"], #rows=[[1, 10], [2, 11], [3, 12]], #hash_rows=nil, #column_types={}>
>> result.each { |row| puts row.inspect }
{"id"=>1, "size"=>10}
{"id"=>2, "size"=>11}
{"id"=>3, "size"=>12}
=> [{"id"=>1, "size"=>10}, {"id"=>2, "size"=>11}, {"id"=>3, "size"=>12}]
If you already have the known keys that you want to extract from the hash, then you can just use Hash#select method as following:
a = [{"id"=>1, "name"=>"Ukraine", "phone_code"=>"+38", "created_at"=>"2015-11-23 21:52:49.415748", "updated_at"=>"2015-11-23 21:52:49.415748", 0=>1, 1=>"Ukraine", 2=>"+38", 3=>"2015-11-23 21:52:49.415748", 4=>"2015-11-23 21:52:49.415748"}]
known_keys = %w(id name phone_code created_at updated_at)
a[0].select { |key, value| known_keys.include? key }
# => {"id"=>1, "name"=>"Ukraine", "phone_code"=>"+38", "created_at"=>"2015-11-23 21:52:49.415748", "updated_at"=>"2015-11-23 21:52:49.415748"}
I am not sure why you are returning in this manner, but in answer to your question "what is the best way to output only elements with proper titles, not with indexes?":
# The new, properly formatted object
hash_of_proper_keys = Hash.new
# Assuming country is in the form of a hash of values
country.each do |key, value|
hash_of_proper_keys[key] = value unless key.is_a? integer
end
I have a datetime column in one of my tables (team_opps) called start_date.
I am trying to write methods in my model that allow me to classify them as Monday, Tuesday, etc... opportunities.
def self.friday_team_opps
where('WEEKDAY(start_date) = ?', 4)
end
In my view I am trying to call a .each on it.
<% TeamOpp.friday_team_opps.each do |team_opp| %>
<%= render team_opp, :team_opp => :team_opp %>
<% end %>
Error is:
SQLite3::SQLException: no such function: WEEKDAY: SELECT "team_opps".* FROM "team_opps" WHERE (WEEKDAY(start_date) = 4)
Thanks
First of all, you need to define the method on the TeamOpp class by defining the method as def self.friday_team_opps.
Moreover, you can't call methods on the column since it would require ActiveRecord to load all the data in your table and then call the Ruby method on that data. What you can do is use direct SQL functions, like for example MySQL's WEEKDAY (monday = 0, tuesday = 1, etc.):
def self.friday_team_opps
where("WEEKDAY(team_opps.created_at) = ?", 4)
end
In SQLite, you can use the strftime function (sunday = 0, monday = 1, etc.):
def self.friday_team_opps
where('strftime("%w", "created_at") = "?"', 5)
end
You define it as an instance method
def friday_team_opps
And it should be defined as a class method
def self.friday_team_opps
If you want to make it a instance function then you should use it like this
def friday_team_opps
return self.start_date.strftime("%A")
end
Subsequently you will have to modify your view like this :
<% TeamOpp.select("start_date").each do |team_opp| %>
<%= team_opp.friday_team_opps() %>
<% end %>
This is my first time serializing. I serialized an array of checkboxes w/ jQuery on the client side, put it into a hidden element, and submitted the form. Now on the server side I want to deserialize into an array I can use. Here is my string on the client side.
someArray%5B%5D=value0&someArray%5B%5D=value1
In Rails 3, I would like to get an array that looks like:
["value0", "value1"]
Thanks!
Rack will automatically parse these values if you submit them as typical post parameters to your request. For example:
curl http://yoursite.com -d "array[]=somevalue&array[]=othervalue"
This will then be available as params[:array] within your application, containing two elements with the values specified.
For serialization i came up with something and i've got working in production for a while.
Lets say i've got a Car model with 3 different type of gadgets. (Lets assume i dont want 3 fields in DB):
in your database must be a field named gadgets as TEXT (ths is very important)
in Car.rb
serialize :gadgets
attr_accessible :alarm, :ac, :tires
ALARM = 0;
AC = 1;
TIRES = 2;
# this is the getter for alarm
def has_alarm
if self.gadgets.nil?
return 0
else
if self.gadgets[ALARM].nil?
return 0
else
return self.gadgets[ALARM]
end
end
# this is the setter for alarm
def has_alarm=(value)
self.gadgets = Array.new if self.gadgets.nil?
self.gadgets[ALARM] = value
end
# getter
def has_ac
if self.gadgets.nil?
return 0
else
if self.gadgets[AC].nil?
return 0
else
return self.gadgets[AC]
end
end
# setter
def has_ac=(value)
self.gadgets = Array.new if self.gadgets.nil?
self.gadgets[AC] = value
end
...
in your _form.rb
<%= f.check_box :has_alarm %> I want alarm in my car
<%= f.check_box :has_ac %> I want AC in my car
<%= f.check_box :has_tires %> I want deluxe tires in my car
I hope you dont have to search by these fields later...
I know how to pass parameters the dumb way. For example,
<%= link_to "Order", new_order_item_path(:item_id => #item.id) %>
The OrderItemsController receives it as params[:item_id] = id.
Problem:
#order_item = OrderItem.new(params)
raises an exception (Can't mass-assign protected attributes: action, controller). I can get around this with the following code.
#order_item = OrderItem.new
#order_item.item_id = params[:item_id]
I know the controller requires params[:order_item][:item_id] for new to work the first way. My question is, how do I get new_order_item_path to generate url? I know this isn't a major problem, but it just bugs me that I don't know the cleaner/proper way to do this. I have tried searching, but only received unrelated questions/answers/results.
Thanks
You didn't really specify if you didn't want to use it or not, but in your model, you could make the attribute item_id accessible like so:
class OrderItem < ActiveRecord::Base
attr_accessible :item_id
...
In this way,
#order_item = OrderItem.new(params)
would work.
Hope this helps.
How about this:
# Controller
def get_item_edit_method
#order = OrderItem.find("your criteria")
##order = OrderItem.new # if new
#item = Item.new()
end
def post_item_edit_method
#order = OrderItem.new(params) # should work now
#order.save
end
# End controller
<!-- view -->
<% #order.item = #item %>
<%= link_to "Order", new_order_item_path(#order) %>
<!-- end view -->
I have in my controller this:
#itemsok = Search.where("first_item_id = ?", params["3"])
This is sopposed to be a query in the search table of the database asking for all the searches that have a first_item_id = 3 ...
Question 1 .- The syntax is I found it in http://guides.rubyonrails.org/active_record_querying.html but im not sure if im using it right?
Ok the question 2 is, I have this on the controller, is it ok to have querys in the controller?
In the view im printing the variable <%= #itemsok %> and all I get is a
ActiveRecord::Relation:0x007fd3d3e894d8
Any suggestions?
Thanks in advance.
ActiveRecord 3 lets you chain relations together so you can do something like this:
#itemsok = Search.where("first_item_id = ?", params["3"]).where("foo = ?", "bar")
The where() function returns an ActiveRecord::Relation. Generally this isn't a problem, since if you use the object it'll automatically run the query and return the results on the object so you'll get the database objects. AR doesn't run the query until it's actually needed.
Where will return a list of items (Array), so if you're just debugging, change your view to this:
<%= debug #itemsok.to_a %>
You seem to be constructing the query wrong way.
If you want to search for records with first_item_id = 3, you should do:
Search.where("first_item_id = ?", 3)
This will return an array of matching records, something you can't easily print with <%= #itemsok %>. You should iterate over the elements and print each one:
<% #itemsok.each do |item| %>
<%= item.name %>
<% end %>
I'd also suggest defining to_s method for the objects you want to print.
class Search
def to_s
name
end
end
Then you can simply print the object and to_s method will be automatically called for you:
<% #itemsok.each do |item| %>
<%= item %>
<% end %>
The right way to do is to define a namedscope in the model and then use it in the controller.
Something similar to this :
class Search < ActiveRecord::Base
named_scope:item_ok,lambda {|*args|{:conditions=>["item_id >= ?", args.first]}}
end
and then call the namedscope from the controller like this :
#itemsok = Search.item_ok(params[:value])