Named Scope Problem With "Has Many Through" Association - ruby-on-rails

I'm using named scopes to process some filtering actions, and the log is showing that everything is working perfectly, except that after the app goes and finds the correct data, it then ignores what it found and just lists a find.all instead of the filtered result. Here's the details.
I have 3 models: Users, Markets and Schedules.
User has_many :schedules
User has_many :markets, :through => :schedules
Market has_many :schedules
Market has_many :users, :through => :schedules
Schedule belongs_to :user
Schedule belongs_to :market
On the "show" page for each market, I display the users who sell things at that market. I also display the days of the week that such users are at the market. This data is contained in the join model (i.e. schedules).
On the market page, I need to support filtering the users by day of the week that the user is at the market.
In my Market controller, I have this:
def show
#market = Market.find(params[:id])
#users = #market.users.filter_marketdate(params[:filter])
end
In my Market model, I have this:
def self.filter_marketdate(filter)
case filter
when 'monday' then monday.all
else find(:all)
end
end
In my User model, I have this:
named_scope :monday, :include => :schedules, :conditions => {'schedules.monday' => true }
AND
def self.filter_marketdate(filter)
case filter
when 'monday' then monday.all
else find(:all)
end
end
In my show view for Markets, I have this:
<%= link_to_unless_current "All", :filter => 'all' %>
<%= link_to_unless_current "Mon", :filter => 'monday' %>
<% #market.schedules.each do |c| %>
<%= link_to c.user.name, c.user %>
<% end %>
Here's the weird part. The following is my log output when I select the Monday filter. If you look at the Select Schedules line of the output, you can see that the query is finding a limited number of user IDs. These are, in fact, the correct user IDs that I want to display for my filtered query. The part I don't understand is that after the app does the query perfectly, it then goes and loads all of the users instead of just the filtered results. I'm not sure what I'm missing.
Processing MarketsController#show (for ip at 2009-09-21 05:19:25) [GET]
Parameters: {"id"=>"1", "filter"=>"monday"}
Market Load (0.8ms) SELECT * FROM "markets" WHERE ("markets"."id" = 1)
User Load (7.3ms) SELECT "users".* FROM "users" INNER JOIN "schedules" ON "users".id = "schedules".user_id WHERE ((("schedules".market_id = 1)) AND ("schedules"."monday" = 't'))
Schedule Load (4.3ms) SELECT "schedules".* FROM "schedules" WHERE ("schedules".user_id IN (16,23,25,30,39,61,73,75,85,95,97,111,112,116,121,123,126,134,136,145,160,165,171,188,189))
Rendering template within layouts/application
Rendering markets/show
Schedule Load (14.3ms) SELECT * FROM "schedules" WHERE ("schedules".market_id = 1)
User Load (0.8ms) SELECT * FROM "users" WHERE ("users"."id" = 2)
User Load (0.8ms) SELECT * FROM "users" WHERE ("users"."id" = 8)
It goes on to list every user who is connected to this particular market, essentially doing a find.all.
UPDATE
In response to Brad's comment below, I tried changing the code in my markets/show view to the following, but I got the same result. I agree that the problem is in here somewhere, but I can't quite figure out how to solve it.
<%= link_to_unless_current "All", :filter => 'all' %>
<%= link_to_unless_current "Mon", :filter => 'monday' %>
<% #market.users.each do |user| %>
<%= link_to user.name, user %>
<% end %>

In your view, you are iterating over each market.schedule, not over the #users variable that you set. In fact, you aren't even using #users in the code you show us.

Shouldnt that be:
#Market.rb
has_many :users, :through => :schedules
Beside this, maybe this plugin helps you:
http://github.com/ntalbott/query_trace
It provides feedback for each sql statement and where it comes from..
f.e.:
Before:
Schedule Load (0.023687) SELECT * FROM schedules WHERE (schedules.id = 3) LIMIT 1
Resource Load (0.001076) SELECT * FROM resources WHERE (resources.id = 328) LIMIT 1
Schedule Load (0.011488) SELECT * FROM schedules WHERE (schedules.id = 3) LIMIT 1
Resource Load (0.022471) SELECT * FROM resources WHERE (resources.id = 328) LIMIT 1
After:
Schedule Load (0.023687) SELECT * FROM schedules WHERE (schedules.id = 3) LIMIT 1
app/models/available_work.rb:50:in `study_method'
app/helpers/plan_helper.rb:4:in `work_description'
app/views/plan/_resource_schedule.rhtml:27:in `_run_rhtml_plan__resource_schedule'
app/views/plan/_resource_schedule.rhtml:24:in `_run_rhtml_plan__resource_schedule'
app/views/plan/_schedule_listing.rhtml:5:in `_run_rhtml_plan__schedule_listing'
app/views/plan/_schedule_listing.rhtml:3:in `_run_rhtml_plan__schedule_listing'
app/views/plan/_schedule_listing.rhtml:1:in `_run_rhtml_plan__schedule_listing'
app/views/plan/index.rhtml:6:in `_run_rhtml_plan_index'
vendor/plugins/textmate_footnotes/lib/textmate_footnotes.rb:60:in `render'
Resource Load (0.001076) SELECT * FROM resources WHERE (resources.id = 328) LIMIT 1
app/models/available_work.rb:54:in `div_type'
app/helpers/plan_helper.rb:6:in `work_description'
app/views/plan/_resource_schedule.rhtml:27:in `_run_rhtml_plan__resource_schedule'
app/views/plan/_resource_schedule.rhtml:24:in `_run_rhtml_plan__resource_schedule'
app/views/plan/_schedule_listing.rhtml:5:in `_run_rhtml_plan__schedule_listing'
app/views/plan/_schedule_listing.rhtml:3:in `_run_rhtml_plan__schedule_listing'
app/views/plan/_schedule_listing.rhtml:1:in `_run_rhtml_plan__schedule_listing'
app/views/plan/index.rhtml:6:in `_run_rhtml_plan_index'
vendor/plugins/textmate_footnotes/lib/textmate_footnotes.rb:60:in `render'
UPDATE:
You have to call
<%= link_to_unless_current "All", :filter => 'all' %>
<%= link_to_unless_current "Mon", :filter => 'monday' %>
<% #users.each do |user| %>
<%= link_to user.name, user %>
<% end %>

Related

Limit scope on rails-jquery-autocomplete (rails3-jquery-autocomplete) gem - where clause issue

There is a recommended solution and it seems to work. The issue is in my where clause and I'm not sure what's wrong.
For reference, here is the solution(s):
https://stackoverflow.com/a/7250426/4379077
https://stackoverflow.com/a/7250341/4379077
I am trying to scope users that are members of the current_user's family tree memberships(branches) user's within my Nodes controller. This would normally be done using this code (current_user.family_tree.memberships).
Note I have successfully set this up to autocomplete showing all users (User.all):
In my routes:
resources :nodes do
get :autocomplete_user_first_name, :on => :collection
end
In my Node controller I have the following code:
autocomplete :user, :first_name, :extra_data => [:last_name, :email],
display_value: :full_name
And in my view I have the following form:
<%= form_for node do |f| %>
<%= f.label :user_tags %>
<%= f.autocomplete_field :user_tags, autocomplete_user_first_name_nodes_path, 'data-auto-focus' => true, value: nil %>
<%= f.submit %>
<% end %>
When I attempt to add the recommended solution to my nodes controller:
def get_autocomplete_items(parameters)
items = super(parameters)
items = items.where(:user_id => current_user.family_tree.memberships)
end
I get this message:
NoMethodError - super: no superclass method "get_autocomplete_items" for #<NodesController:0x007fc516692278>:
So, I found this article https://stackoverflow.com/a/18717327/4379077 and changed it to
def get_autocomplete_items(parameters)
items = active_record_get_autocomplete_items(parameters)
items = items.where(:user_id => current_user.family_tree.memberships)
end
It works, but I get the following error
PG::UndefinedColumn: ERROR: column users.user_id does not exist, so I changed the where clause to this :id => current_user.family_tree.memberships and I get this result
User Load (0.9ms) SELECT users.id, users.first_name, "users"."last_name",
"users"."email"
FROM "users" WHERE (LOWER(users.first_name) ILIKE 'mi%')
AND "users"."id" IN (SELECT "memberships"."id" FROM "memberships"
WHERE "memberships"."family_tree_id" = $1)
ORDER BY LOWER(users.first_name) ASC LIMIT 10 [["family_tree_id", 1]]
The issue is that I believe I need to get a collection within the membership model comparing the attribute membership.user_id to user.id. What am I doing wrong in my where clause?
Are Membership objects the same thing as Users?
if not, you need to get the user_id off the membership record
This line would need to change
# use pluck to get an array of user_ids.
items = items.where(:id => current_user.family_tree.memberships.pluck(:user_id))

Rails test for contents in a form

I have a Comment form that also contains an Attachment form.
Comment model contains:
accepts_nested_attributes_for :attachments
Comment form contains:
<%= f.fields_for :attachments do |builder| %>
<%= builder.input :name, :label => 'Attachment Name' %>
<%= builder.file_field :attach %>
<% end %>
Comment Controller contains:
def new
#comment = Comment.new
#comment.attachments.build
If the user adds an Attachement, everything works fine.
I would like the user to be able to submit a Comment with or without an Attachment.
Right now, if the user enters a Comment without an attachment, the form re-displays and the Comment does not get created.
This is the log if I try to post a new Comment without an Attachement:
Started POST "/comments" for 127.0.0.1 at 2013-12-19 10:34:31 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"A6MOeMgoGUDmGiJr9PWinHVTAa7X63fgtA7+2my0A2Y=", "comment"=>{"user_id"=>"1", "status_date"=>"2013-12-19", "worequest_id"=>"10", "statuscode_id"=>"", "comments"=>"test", "attachments_attributes"=>{"0"=>{"name"=>""}}}, "_wysihtml5_mode"=>"1", "commit"=>"Save Comment"}
Tenant Load (0.3ms) SELECT "tenants".* FROM "tenants" WHERE "tenants"."subdomain" = 'ame' LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."tenant_id" = 1 AND "users"."id" = 1 LIMIT 1
(0.1ms) BEGIN
(0.1ms) ROLLBACK
I need to figure out the right code so that the Attachment fields show up in the form, but the Comment will get created if no Attachment is selected.
Maybe I need to put code in the Attachment controller?
You could use Rails present? method to check if the object is not blank:
#comment.attachments.build if #comment.attachments.present?
I changed the Comment model to this:
accepts_nested_attributes_for :attachments, :reject_if => lambda { |a| a[:attach].blank? }, :allow_destroy => true

Rails, how to use searchlogic to reorder returned objects

So I have had various forms of this working in the last while, but never all working together.
for reference I have categories / Brands / Products, with the right relationships working: the site is http://emeraldcityguitars.com to see it in action.
So in my brands controller show action:
#category = Category.find_by_url_name(params[:category_id])
#brand = Brand.find(params[:id])
#search = Product.brand_id_equals(#brand.id).category_id_equals(#category.id).descend_by_price
#products = #search.paginate(:page => params[:page])
this works fine, as is evidenced in my log:
Category Load (25.6ms) SELECT * FROM "categories"
Category Load (0.2ms) SELECT * FROM "categories" WHERE ("categories"."url_name" = 'acoustic-guitars') LIMIT 1
Brand Load (0.6ms) SELECT * FROM "brands" WHERE ("brands"."id" = 14)
Product Load (4.8ms) SELECT * FROM "products" WHERE ((products.category_id = 3) AND (products.brand_id = 14)) ORDER BY products.price DESC LIMIT 6 OFFSET 0
SQL (0.2ms) SELECT count(*) AS count_all FROM "products" WHERE ((products.category_id = 3) AND (products.brand_id = 14))
Rendering template within layouts/application
Rendering brands/show
You can see that its grabbing products descending by price.
In my Brand#show I am doing the following:
<%- form_for [#category, #brand], :html => {:method => 'get', :id => 'sort_form', :class => 'sort_form'} do -%>
<label>Sort by: </label> <%= select_tag :order, product_sort_options %>
<%= submit_tag 'Go' %>
<%- end -%>
The goal being that a user could sort by a couple different options.
I also have this in my products_helper:
def product_sort_options
options_for_select([
['', nil],
['Newest to Oldest', 'descend_by_date'],
['Oldest to Newest', 'ascend_by_date'],
['Price: Highest to Lowest', 'descend_by_price'],
['Price: Lowest to Highest', 'ascend_by_price'],
['Name', 'ascend_by_name']
])
end
The issue I am having is that if I click the drop down and do price lowest to highest it reloads the page, with "?order=ascend_by_price" at the end of the url but there is no change in the order of the products.
any help is appreciated.
You'll need to add in a call to include the value of your :order parameter. It only gets included in the search by default if you're doing something like Product.search(params[:search]) (and the order parameter would then have to be in params[:search][:order]).
So, something like this should work:
#search = Product.brand_id_equals(#brand.id)
#search.category_id_equals(#category.id)
#search.order(params[:order] || :descend_by_price)
I've split it out to make it easier to read. The last line specifies to order by the value of your order parameter or the default ordering if that's not available.

How to make a search form with acts_as_taggable

I have a search form to search for images by their tags. The form kinda works, it sends the parameters to the /search_results page but it sends as this:
search_results?utf8=✓&search=squid%2C+color&x=0&y=0
And here is my form:
<%= form_tag ("/search_results"), :method => "get", :class=>"search_form" do %>
<%= text_field_tag ("search"), nil, :class => 'search_input',
:onblur=>"if(this.value=='')this.setAttribute('class', 'search_input');",
:onfocus=>"this.setAttribute('class', 'search_input_clear');"
%>
<%= image_submit_tag("search.png") %>
<% end %>
and and my route/controller:
match "/search_results/" => "index#search_results", :via => :get, :as =>"search_results"
class IndexController < ApplicationController
def search_results
#tattoos = Tattoo.tagged_with("%#{params[:search]}%")
end
But I never get any results.
Rails console shows this:
Parameters: {"utf8"=>"✓", "search"=>"color, animals", "x"=>"0", "y"=>"0"}
SQL (0.5ms) SHOW TABLES
ActsAsTaggableOn::Tag Load (0.2ms) SELECT `tags`.* FROM `tags` WHERE (name LIKE '\\%color' OR name LIKE 'animals\\%')
SQL (0.1ms) SELECT COUNT(*) FROM `tattoos` WHERE (1 = 0)
Tattoo Load (0.3ms) SELECT `tattoos`.* FROM `tattoos` WHERE (1 = 0) ORDER BY tattoos.created_at DESC
I removed the % surrounding my params and that seemed to do the trick:
def search_results
#tattoos = Tattoo.tagged_with("#{params[:search]}")
end

Nested form using accepts_nested_attributes_for with pre-population from another table

I'm using Rails 2.3.5 and have a nested structure as follows:
Lists has_many Items
Items_Features has_many Features
Items_Features has_many Items
Items_Features has a text field to hold the value of the feature
Then I have a nested form with partials to update and display this so that it updates Lists, Items and Items_Features
What I want to do is generate input fields for each of the rows in features so that the user can fill in a value and it gets inserted/updated in items_features. I also want a label next to the box to display the feature name.
It might look like this:
List name: Cheeses
Item1 name: Edam
Feature, hardness: - fill in - <= this list of features from feature table
Feature, smell: - fill in -
How can I interrupt the nice and easy accepts_nested_attributes_for system to display this as I want?
EDIT:
Here's the code for the Item class now i've got some sql in there:
class Item < ActiveRecord::Base
belongs_to :list
has_many :users
has_many :votes
has_many :items_features
validates_presence_of :name, :message => "can't be blank"
accepts_nested_attributes_for :items_features, :reject_if => lambda { |a| a.values.all?(&:blank?) }, :allow_destroy => true
def self.get_two_random(list_id)
Item.find_by_list_id(list_id, :limit => 2, :order => 'rand()')
end
def self.get_item_features(item_id)
sql = "select items_features.*, features.id as new_feature_id, features.name as feature_name "
sql += "from items_features "
sql += " right outer join features "
sql += " on features.id = items_features.feature_id "
sql += " left outer join items "
sql += " on items.id = items_features.item_id "
sql += "where items_features.item_id = ? or items_features.item_id is null"
find_by_sql([sql, item_id])
end
end
Here's my display code - I need to save the feature_id into new records somehow:
<% form_tag item_path, :method => :put do %>
<% for items_feature in #item_features %>
<% fields_for "items_features[]", items_feature do |f| %>
<%=h items_feature.feature_name %> <%= f.text_field :featurevalue %><br><Br>
<% end %>
<% end %>
<p><%= submit_tag "Submit"%></p>
<% end %>
Hmm, that isn't working - it prints out fine but then the server gives me:
/!\ FAILSAFE /!\ Thu Apr 15 16:44:59 +0100 2010
Status: 500 Internal Server Error
expected Array (got Hash) for param `items_features'
When I post it back
Try the examples here
http://github.com/ryanb/complex-form-examples

Resources