I know how to access foreign key attributes in a scaffold index view. I can simply refer to the attributes using dot notation such as property.que.name. Given the following models:
class Priority < ActiveRecord::Base
belongs_to :que
...
end
class Que < ActiveRecord::Base
has_many :priorities
...
end
In the index view, I can do something like this to get the name value:
<td><%=h priority.que ? priority.que.name : "" %></td>
How do I do this in the jqgrid?
I tried this but the jqgrid comes back empty:
Priorities Controller:
#priorities = Priority.find(:all, :order => "position", :conditions => "multitenant_team_id = " + current_user.team.id.to_s ) do
if params[:_search] == "true"
id =~ "%#{params[:id]}%" if params[:id].present?
issue_id =~ "%#{params[:issue_id]}%" if params[:issue_id].present?
que =~ "%#{params[:que]}%" if params[:que].present?
customer =~ "%#{params[:customer]}%" if params[:customer].present?
title =~ "%#{params[:title]}%" if params[:title].present?
reporting_source =~ "%#{params[:reporting_source]}%" if params[:reporting_source].present?
priority =~ "%#{params[:priority]}%" if params[:priority].present?
product =~ "%#{params[:product]}%" if params[:product].present?
current_owner =~ "%#{params[:current_owner]}%" if params[:current_owner].present?
end
paginate :page => params[:page], :per_page => params[:rows]
order_by "#{params[:sidx]} #{params[:sord]}"
end
if request.xhr?
end
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #priorities.to_jqgrid_json(
[:id, :issue_id, :que.name, :customer, :title, :reporting_source,
:priority, :product, :current_owner],
params[:page], params[:rows], #priorities.total_entries)}
format.xml { render :xml => #priorities }
end
end
Index View:
<%= jqgrid("Priorities", "priorities", "/priorities",
[
{:field => "id", :label => "ID", :width => 35, :resizable => false},
{:field => "issue_id", :label => "Issue Id"},
{:field => "que", :label => "Queue"},
{:field => "customer", :label => "Customer"},
{:field => "title", :label => "Title"},
{:field => "reporting_source", :label => "Reporting Source"},
{:field => "priority", :label => "Priority"},
{:field => "product", :label => "Product"},
{:field => "current_owner", :label => "Current Owner"}
],
{ :rows_per_page => 12, :height => 450 }
)%>
If I specify que instead of que.name, I get the data back in the grid but the Queue field shows a "#" symbol so I suspect the .to_jqgrid_json call doesn't like my syntax.
Has anyone tried this before? I hope so.
I fixed my problem. I ended up changing my find to a find_by_sql so I could do a left outer join on the ques table. I think there were a couple of issues. I think the *to_jqgrid_json* had problems with null foreign key values and I couldn't figure out how to get at the Que.name any other way. I'm using SQLServer so I had to use isnull(ques.name, '') to convert the null to empty space.
So I replaced my find as follows:
#priorities = Priority.find_by_sql ["select priorities.id id, issue_id, isnull(ques.name,' ') queue_name, customer, title, reporting_source, priority, product, current_owner from priorities left outer join ques on priorities.que_id = ques.id where priorities.multitenant_team_id = ? order by issue_id", current_user.team.id.to_s]
This introduced another problem in that find_by_sql returns an array which breaks the #priorities.total_entries call. So I had to replace it with array.count.
format.json { render :json => #priorities.to_jqgrid_json(
[:id, :issue_id, :queue_name, :customer, :title, :reporting_source, :priority, :product, :current_owner],
params[:page], params[:rows], #priorities.count)}
My grid looks great!
Edit
My grid LOOKS great but it doesn't paginate or sort. Back to the drawing board. :(
Okay, I think I fixed it for real this time.
#priorities = Priority.find(:all,
:select => "priorities.id, priorities.issue_id,
priorities.customer, priorities.title,
priorities.reporting_source, priorities.priority,
priorities.product, priorities.current_owner,
priorities.position,
isnull(ques.name,' ') queue_name",
:joins => "LEFT OUTER JOIN ques ON ques.id = priorities.que_id",
:order => "priorities.position",
:conditions => "priorities.multitenant_team_id = " + current_user.team.id.to_s ) do
I had know idea I could specify joins like this. This keeps the resultset in a format the 2dc_jqgrid plugin likes. Sorting, pagination and searching all work now. Now my grid looks good and actually works.
Related
I would like to add has_many models LoanAmtPerSvcType to LoanContract array.
Below is my code, but it does not work.
When i check #contracts[0].loan_amt_per_svc_type.count , it return '0'
#members.each do |c|
#contracts << LoanContract.new(
:customer_id => c.id,
:season_id => #season.id,
:loan_type_id => #loan_type.id,
:cus_group_id => #group.id,
contract_date: #contract_date,
loan_duration: #loan_duration,
inspector_id: #inspector.id,
mgr_id: #manager.id,
user_id: #user.id)
end
#contracts.each do |lc|
lc.loan_amt_per_svc_type = [LoanAmtPerSvcType.new(customer_service_type_id: 1), LoanAmtPerSvcType.new(customer_service_type_id: 2)]
end
render :text => #contracts[0].loan_amt_per_svc_type.count
#contracts[0].loan_amt_per_svc_type.count return 0, because you didn't save your contracts into the database.
You can use LoanContract.create instead of LoanContract.new. Also with associations.
If you only want to know count of loan_amt_per_svc_type use size method.
#contracts[0].loan_amt_per_svc_type.size
On rails 4 with the acts as taggable gem. My search is currently not returning exact matches first. It seems to be like the tags aren't being weighted properly. When I get rid of the :associated_against => { :tags => {:name => 'D'}} exact matches are returned first. Has anyone ran into this issue before? Any suggestions?
Here is my search scope:
pg_search_scope :search, :against => { :specific => 'A', :title => 'B', :aka => 'B'},
:associated_against => { :tags => {:name => 'D'}},
:using => { dmetaphone: {}, tsearch: { dictionary: 'english' },
trigram: {:threshold => 0.3} },
ignoring: :accents
Can you post the rest of your code in the controller, etc. I have the following in my app:
# tools.rb
include PgSearch
pg_search_scope :search_including_tags,
:against => [:description, :barcode],
:associated_against => {:tags => [:name] }
Then in my controller to search through I have:
#tools_controller.rb
def index
if params[:search]
#tools = Tool.where("(barcode) LIKE (?)", "%#{params[:search]}")
elsif params[:tag]
#tools = Tool.tagged_with(params[:tag])
elsif params[:id]
#tool = Tool.find(params[:id])
else
#tools = Tool.all
#tool = Tool.first
end
end
and finally for my search controller
def new
#tools = Tool.search_including_tags(params[:query])
end
Hope this helps. Can't really say much without seeing all of the code. But I ended up using this which worked: :associated_against => {:tags => [:name] }
I have view that created from сontributed API
=form_tag add_group_vk_vk_entries_path, method: :put do
-length_of_array = #vk_groups['message']['vk'].length
.row-fluid
-#vk_groups['message']['vk'][1..length_of_array].each do|item|
.span4
p= check_box_tag "vk_groups[]", item['gid']
p=item['name']
p=image_tag item['photo'], :size => "100x100",:class => "img-circle"
= submit_tag "ok"
I want to sent the data from this api to my controller by check_box_tag. I want to send not only item['gid'] i want to sent to my controller all data that i checked through one check_box_tag but i don't anderstand how.
In my controller
def add_group_vk
params[:vk_groups].each do |item|
if VkEntry.not_exists?(item) == true
VkEntry.create!(
:git => item
)
end
end
redirect_to vk_entries_url
end
i want something like this
def add_group_vk
params[:vk_groups].each do |item|
if VkEntry.not_exists?(item) == true
VkEntry.create!(
:git => item[:gid],
:name=> item[:name],
:ser=> item[:ser],
:photo=> item[:photo]
)
end
end
redirect_to vk_entries_url
end
First, I'm assuming that your above generates the check boxes with names like:
vk_groups[100], vk_groups[101],...
All you can really extract is a list of id's, they're in the the hash key, the value is not important.
params[:vk_groups] will yield a hash, iterate over the hash like so
def add_group_vk
params[:vk_groups].each do |key,val|
if VkEntry.not_exists?(key) == true
VkEntry.create!(
:git => key,
:name=> item[:name],
:ser=> item[:ser],
:photo=> item[:photo]
)
end
end
redirect_to vk_entries_url
end
As a result i done:
def add_group_vk
params[:vk_groups].each do |key,val|
item = eval val
if VkEntry.not_exists?(key) == true
VkEntry.create!(
:gid => key,
:name => item['name'],
:screen_name => item['screen_name'],
:is_closed => item['is_closed'],
:is_admin => item['is_admin'],
:is_member => item['is_member'],
:type_vk => item['type_vk'],
:photo => item['photo'],
:photo_medium => item['photo_medium'],
:photo_big => item['photo_big']
)
end
end
redirect_to vk_entries_url
end
In view
p= check_box_tag "vk_groups[#{item['gid']}]", item
I have an index view that lists all of the tags for my Entry and Message models. I would like to only show the tags for Entries in this view. I'm using acts-as-taggable-on.
Tags Controller:
def index
#letter = params[:letter].blank? ? 'a' : params[:letter]
#tagged_entries = Tagging.find_all_by_taggable_type('Entry').map(&:taggable)
#title = "Tags"
if params[:letter] == '#'
#data = Tag.find(#tagged_entries, :conditions => ["name REGEXP ?",
"^[^a-z]"], :order => 'name', :select => "id, name")
else
#data = Tag.find(#tagged_entries, :conditions => ["name LIKE ?",
"#{params[:letter]}%"], :order => 'name', :select => "id, name")
end
respond_to do |format|
flash[:notice] = 'We are currently in Beta. You may experience errors.'
format.html
end
end
tags#index:
<% #data.each do |t| %>
<div class="tag"><%= link_to t.name.titleize, tag_path(t) %></div>
<% end %>
I want to show only the taggable type 'Entry' in the view.
Any ideas? Thank you for reading my question.
SECOND EDIT:
Tags Controller:
def index
#title = "Tags"
#letter = params[:letter].blank? ? 'a' : params[:letter]
#taggings = Tagging.find_all_by_taggable_type('Entry', :include => [:tag, :taggable])
#tags = #taggings.map(&:tag).sort_by(&:name).uniq
#tagged_entries = #taggings.map(&:taggable)#.sort_by(&:id)#or whatever
if params[:letter] == '#'
#data = Tag.find(#tags, :conditions => ["name REGEXP ?",
"^[^a-z]"], :order => 'name', :select => "id, name")
else
#data = Tag.find(#tags, :conditions => ["name LIKE ?",
"#{params[:letter]}%"], :order => 'name', :select => "id, name")
end
respond_to do |format|
format.html
end
end
tags#index:
<% #data.each do |t| %>
<div class="tag"><%= link_to t.name.titleize, tag_path(t) %></div>
<% end %>
Max Williams' code works except when I click on my alphabetical pagination links. The error I'm getting [after I clicked on the G link of the alphabetical pagination] reads:
Couldn't find all Tags with IDs (77,130,115,...) AND (name LIKE 'G%') (found 9 results, but was looking for 129)
Can anyone point me in the right direction?
#taggings = Tagging.find_all_by_taggable_type('Entry', :include => [:tag, :taggable])
#tags = #taggings.map(&:tag).sort_by(&:name)
#tagged_entries = #taggings.map(&:taggable).sort_by(&:id)#or whatever
I have a few constants which are arrays that I don't want to create databse records for but I don't know where to store the constants without getting errors.
For example
CONTAINER_SIZES = [["20 foot"],["40 foot"]]
Where can I store this so all models and controller have access to this?
I will write my way to you.
class User < ActiveRecord::Base
STATES = {
:active => {:id => 100, :name => "active", :label => "Active User"},
:passive => {:id => 110, :name => "passive", :label => "Passive User"},
:deleted => {:id => 120, :name => "deleted", :label => "Deleted User"}
}
# and methods for calling states of user
def self.find_state(value)
if value.class == Fixnum
Post::STATES.collect { |key, state|
return state if state.inspect.index(value.to_s)
}
elsif value.class == Symbol
Post::STATES[value]
end
end
end
so i can call it like
User.find_state(:active)[:id]
or
User.find_state(#user.state_id)[:label]
Also if i want to load all states to a select box and if i don't want some states in it (like deleted state)
def self.states(arg = nil)
states = Post::STATES
states.delete(:deleted)
states.collect { |key, state|
if arg.nil?
state
else
state[arg]
end
}
end
And i can use it now like
select_tag 'state_id', User.states.collect { |s| [s[:label], s[:id]] }
I put them directly in the model class.
class User < ActiveRecord::Base
USER_STATUS_ACTIVE = "ACT"
USER_TYPES = ["MANAGER","DEVELOPER"]
end