rails activerecord multiple query - ruby-on-rails

Thanks for your time !
It's a simple question but I've searched for some time and still cannot get the function suit me.
I get a table named *lr_transaction_tables* in DB and a class LrTransactionsTable < ActiveRecord::Base with it.
I can #entry_ary = LrTransactionsTable.find(:all) to fetch the whole table and present it in the view by :
<table id="trans-war-table">
<% #entry_ary.each do |item| %>
<tr>
<td><%= item.ltname %></td>
<td><%= item.name %></td>
</tr>
<% end %>
</table>
But how do I get the data where the data under ltname column is "specific word" instead of all of it.
I've tried #entry_ary = LrTransactionsTable.find_by_ltname( "specific word" ), but it give me the error that undefined methodeach' for nil:NilClass`
ltname and name is the column name in the table.

For Rails 2
LrTransactionsTable.find(:all, :conditions => {:ltname => "specific word"})
For Rails 3
#entry_ary = LrTransactionsTable.where(ltname: "specific word")
OR
#entry_ary = LrTransactionsTable.where(["ltname =? ", "specific word"])

I'll use the where method to set a condition:
LrTransactionsTable.where(:ltname => "specific word")

try best way, always right query in model
in your controller
LrTransactionsTable.find_ltname("specific word")
and write in your model
def find_ltname(name)
where("ltname = ?", name)
end
or you can also create a scope for that
scope :find_ltname, lambda{|name|{ :conditions => ["ltname = ?", name]}

try this:
#entry_ary = LrTransactionsTable.where(ltname: "specific word")

Related

How to get name of foreign key

In my Rails app I have a list view of device ports and each device port belongs to a device:
device.rb
has_many :device_ports, :foreign_key => "device_id"
device_port.rb
belongs_to :device
device_port_controller.rb
def list
#device_ports = DevicePort.paginate(:all, :page => params[:page], :per_page => 100, :order => "name")
#devices = Device.find(:all)
end
list.rhtml
<table width="100%">
<tr>
<th>Name</th>
<th>Device</th>
</tr>
<%= render :partial => 'device_port/list_item', :collection => #device_ports %>
</table>
_list_item.rhtml
<tr>
<td><a href='/device_port/update/<%= list_item.id %>'><%= list_item.name %></a></td>
<td><%= list_item.device_id %></td>
</tr>
So I am displaying the device_id from the device_ports table but I actually want to display the name column of the devices table instead.
I have done something very similar and probably slightly more difficult elsewhere in my app where I have a preselected dropdown with the correct device name selected but I can't seem to figure out how to do it outwith the context of a select menu.
I have the devices in the #devices variable in the controller above and was trying to look that up using the list_item.device_id but it didn't seem to work.
It's probably quite a straightforward thing but I just can't seem to find the proper way of getting the desired result.
as device_ports belongs_to device so list_item.device.name Thanks!
I just tested this out in the console but it should work. You can call columns on your model which returns an array.
So, what I just used my User model:
User.columns[0].name #=> 'id'
Presumably yours will be
Device.columns[x].name
EDIT: I read the the question as "name [of the] column"

Rails - how to return just text of an ActiveRecord record

I have a model of cities and one of the attributes is the city 'name'.
I've done a helper method to return 'n' number of cities and the implementation is below:
helper method:
def list_cities(start, stop)
cities = City.find(:all, order: "name asc", limit: stop-start, select: "name")
cities.each do |city|
"<li> #{city.name} </li>"
end
end
view code:
<%= list_cities(1,22) %>
However, it returns the following in the view:
[#<City name: "Abilene">]
How do I get just the text of the city name and get rid of the rest of the query?
The problem is that your method list_cities does not return the string you think it does. It just returns an array of city objects because that's what the method each does. It looks like you're mixing controller and view logic into a helper. What I'd do is:
Set a #cities instance variable in the controller:
#cities = City.find(:all, order: "name asc", limit: stop-start, select: "name")
In the view:
<% #cities.each do |city| %>
<li><%= city.name %></li>
<% end %>
This way you keep your controller and view logic separated.
What Erez answered is the best way to approach this issue. But I'd like to share what you can do to your method to achieve what you want with minimal changes. You need to change your helper to the following
def list_cities(start, stop)
cities = City.all(order: 'name ASC', limit: stop - start, select: 'name')
cities.map { |city| "<li> #{city.name} </li>" }.join.html_safe
end
The other changes are just small refactors to reduce code. Without knowing the rails version you're using, I didn't change the query but if you're using 3.2, you should have access to pluck which is faster since it won't create ActiveRecord objects.
Try:
def list_cities(start, stop)
content = ''
cities = City.find(:all, order: "name asc", limit: stop-start, select: "name")
cities.each do |city|
content << "<li> #{city.name} </li>\n"
end
content
end

Retrieve complex parameter from view Rails 3.1

I'm creating a Rails 3.1 app and I've the following big issue: I must retrieve some parameter from view to controller
This is my view:
<tr class="<%= cycle("odd", "even") %>">
<td><%= text_field_tag("bulk_warehouse_serial#{#count}_page#{params[:page]}", bulk_warehouse.serial, :disabled => true) %></td>
<td><%= text_field_tag("bulk_warehouse_asset#{#count}_page#{params[:page]}", bulk_warehouse.asset, :disabled => true)%></td>
<td><%= check_box_tag "enable_record#{#count}_page#{params[:page]}",1,false,{:onclick => "bulk_warehouse_serial#{#count}.disabled =
bulk_warehouse_asset#{#count}.disabled =
!this.checked;"}%></td>
<td class="last">
<%= link_to "#{t("web-app-theme.delete", :default => "Delete")}", bulk_warehouse_path(bulk_warehouse), :method => :delete, :confirm => "#{t("web-app-theme.confirm", :default => "Are you sure?")}" %>
</td>
</tr>
</div>
<% #count = #count +1 %>
And in my controller I've something such as:
...
#count = 0
...
and this what is generated by web server log:
"warehouse"=>{"asset"=>"turiturira", "serial"=>"caricarira", "project_id"=>"1", "hardware"=>{"brand_id"=>"21"}, "hardware_id"=>"60", "state_id"=>"4", "position_id"=>"1", "logicalwarehouse_id"=>"3", "extra_id"=>"3"}, "bulk_warehouse_serial270"=>"t", "bulk_warehouse_asset270"=>"test", "enable_record2_page0"=>"1", "bulk_warehouse_serial2"=>"uela2", "bulk_warehouse_asset2"=>"bela2", "enable_record3_page0"=>"1"}_
e
Now, in my controller I need an action where I must check first all "enable_record#{#count}_page#{params[:page]}" values and then doing some actions. How can I make if statement in my controller? I was thinking something such as:
#count=0
#page = params[:page]
#count_max = 10
until #count == #count_max
if params[:warehouse][:enable_record#{#count}_page#{params[:page]}] == 1
...doing something...
end
#count=#count+1
end
but it gives me an surror; any suggestions?
This seems quite complicated for whatever it is you're trying to do, but I'll refrain from refactoring your approach. There is one standout in your code however -- it is the dynamic construction of the key you're using. You may want to construct it with a string then 'symbolize' it:
key = "enable_record#{#count}_page#{params[:page]}".to_sym
if params[:warehouse][key] == 1
...doing something...
end
Note: you also might reconsider the equality condition. The hash's value may not be an integer 1 as your code suggests and could actually be "1" (a string). Ensure both values are the same type (using either .to_s or .to_i) if there's any uncertainty.

Next and Previous records

In my show.html.erb file I have two links for next and previous like so
<%= link_to("Previous Post", #question.previous) if #question.previous %>
<%= link_to("Next Post", #question.next) if #question.next %>
.previous and .next are methods in my model which finds either the current id + 1 or - 1
like so in my model
def previous
Question.find_by_id(id - 1, :select => 'id')
end
def next
Question.find_by_id(id + 1, :select => 'id')
end
But rather than incrementing and decrementing blindly as I might have deleted a "Question" so i'll get an error, could I find the next/previous "Question" from the scope of the query the show action was accessed from?
Have you tried something like this?
def previous
Question.limit(1).order("id DESC").where("id < ?", id)
end
def next
Question.limit(1).order("id DESC").where("id > ?", id)
end
Try Act as Ordered.
https://github.com/imedo/acts_as_ordered

Is there anyway to change sort_link output params?

I wanna make a page that contains more than one tables. Each table is ajax filtered table that can be sorted using metasearch. This is sorting link for each table.
Controller SomeController:
def index
#search = FirstTable.search(params[:search])
#first_tables = #search.all
#search_second_table = SecondTable.search(params[:search_second_table])
#second_tables = #search_second_table.all
...
end
View:
# First table
sort_link #search, :some_attribute, "Some Attribute"
#=> www.example.com/some_controller?search[meta_sort]=some_attribute.asc
# Second table
sort_link #search_second_table, :some_attribute, "Some Attribute"
#=> www.example.com/some_controller?search[meta_sort]=some_attribute.asc
I have no idea why the sort_link outputting the same link or maybe I've made some mistake. Is there anyway to change the output of second_table sort_link to be like this.
#=> www.example.com/some_controller?search_second_table[meta_sort]=some_attribute.asc
Thx for your help.
solved my problem using link_to. after click "Some Attribute" link, change the "meta_sort" params to desc using jquery, right after ajax response return successfully. link_to "Some Attribute", :controller => "some_controller", :search_second_table => {:meta_sort => "some_attribute.asc"}

Resources