Why won't my Rails model save into the Database? - ruby-on-rails-3

def self.build_prior_month(payee, as_of = Time.current, opts = {})
start_date, end_date, year, month = effective_dates(as_of)
statement = payee.earnings_statements.build(
:year => year,
:month => month,
:balance => 0,
:revenue => 0
)
statement.generate(start_date, end_date, year, month)
statement.update_totals
statement
end
That's a function that I have in a model of mine. It returns statement properly, but doesn't save to the database. Why is that?
The generate function looks like:
def generate_ledger_items(start_date, end_date, year, month)
payee.ledger_entries.for_month_and_year(month, year).each do |entry|
earnings_statement_items.build(
:items => entry.item_group,
:units => entry.units,
:net_revenue => entry.net_revenue,
:net_revenue_per_unit => [entry.net_revenue, entry.units].all? ? (entry.net_revenue / entry.units).round(2) : nil,
:fees => entry.service_fees,
:payments_collected => entry.spendings,
:fee_terms => entry.terms || entry.description, # When would terms be set?
:due => entry.credit || -entry.debit
)
end
end
def update_totals
self.revenue = earnings_statement_items.net_revenue
self.balance = earnings_statement_items.total
end

The build method on your association does not actually save the record into the database. create will. It is similar to the difference between new and create on your models.
statement = payee.earnings_statements.create(
:year => year,
:month => month,
:balance => 0,
:revenue => 0
)
Will save your record. See the documentation.

.build doesn't save the object
call:
statement.save

Related

How to do multiple where statements for the same column in ActiveRecord?

Using rails 3, How could one do multiple where statements without complicated stuff or extra gems?
Im having this column "accepted" and would like to get all the values where accepted == false and accepted == null
Both of examples below fail:
#scholars = Scholars.where(:scholar_id => current_user.id).where(["accepted = ? or accepted = ?", true, null])
and
#scholars = Scholars.where(:scholar_id => current_user.id).where(:accpeted => true).where(:accepted=> null)
Try:
#scholars = Scholars.where(:scholar => current_user, :accepted => true).all +
Scholar.where(:scholar => current_user, :accepted => nil).all
Did you name your model "Scholars"? Models are traditionally singular... if you named it properly, this should be Scholar.where(...).
The correct answer should be
#profiles = Profile.where(:user_id => current_user.id, :accepted => [true, nil]).order(:accepted)

complex search with thinking sphinx

I'd like to do a complex search with thinking sphinx:
Search for users which:
-> live in a city (city_id attribute)
-> or has hability to move to a city (mobile_cities association)
-> or live at a maximum distance from a lat/long point, the maximum distance is different for each user and set in a mobility_distance attribute.
For now I did that with 3 differents search, I volontary set a big per_page number, then i merge the 3 results on a single array, an then paginate this array :
#users living in the #city
search_set_living = search_set.merge({:city_id => #city.id })
users_living = User.search :with => search_set_living.dup,
:page => 1, :per_page => 1000
#users declaring hability to move to the #city
search_set_mobile = search_set.merge({:mobile_cities_ids => #city.id })
users_mobile = User.search :with => search_set_mobile.dup, :page => 1, :per_page => 1000
#users living at a maximum distance from the origin point(custom distance for each user, max 30km)
search_set_around = search_set.merge({"#geodist" => 0.0..30_000.0})
users_around = User.search :geo => [#search_latitude * Math::PI / 180 , #search_longitude * Math::PI / 180],
:with => search_set_around.dup,
:page => 1, :per_page => 1000
users_around_filtered = users_around.dup.delete_if{|user| (user.mobility_distance * 1000 )< user.sphinx_attributes['#geodist'] }
#merge the 3 results in a array
all_users = (users_mobile.flatten + users_around_filtered.flatten).uniq
#look for facets and paginate the array
#facets = User.facets :with => {:user_id => all_users.map(&:id)}
#users_to_display = all_users.paginate(:page => params[:page], :per_page => 10)
This is working fine but i'm not satisfied:
-performance are not so good,
-I want the ability to sort on multiple attributes like this :order => "created_at DESC, #relevance DESC"
I want to do the exact same search but in a single sphinx's search.
I know that I should use the "OR Logic with Attribute Filters" from the docs but I don't know how to mix it with a geo_search call...
I really have no idea how to do that,
can you guys help me ?
Many thanks,
The :sphinx_select option is definitely your friend here, as you've guessed. Let's piece it together bit by bit:
logic = [
"city_id = #{#city.id}",
"IN(mobile_cities_ids, #{#city.id}",
"GEODIST(lat, lng, #{lat}, #{lng}) < (mobility_distance * 1000)"
]
User.search :sphinx_select => "*, #{logic.join(" OR ")}) AS valid",
:with => {:valid => true}
Add pagination as you like, tweak the attribute names if needed (maybe your lat/lng attributes are named something else). I don't think you need the IF call around that custom attribute like in the docs, but if things aren't working when they should be, maybe give it a shot. Should be good in a facets call too.
Great ! Thank you so much. I just needed to correct a little your syntax (some parenthesis missing) in order to get it work.
I had to add per_page and page arguments too, don't know really why.
logic = ["city_id = #{#city.id}",
"IN(mobile_cities_ids, #{#city.id})",
"GEODIST(latitude, longitude, #{#search_latitude * Math::PI / 180}, #{#search_longitude * Math::PI / 180}) < (mobility_distance * 1000)"]
search_set_logic = search_set.merge({:valid => true})
#users_to_display = User.search :sphinx_select => "*, (#{logic.join(" OR ")}) AS valid",
:with => search_set_logic.dup,
:sort_mode => :extended,
:order => "visibility DESC, last_login_at DESC",
:page => params[:page], :per_page => 10

No MethodError when trying get active record id

In model:
def self.get_by_slug(slug)
self.where("slug = ?", slug)
end
In controller:
#route: match '/category/:slug', :to => 'category#index', :as => "category_jobs"
#category = Category.get_by_slug(params[:slug])
#jobs = Job.where("category_id = ? AND expires_at > ?", #category.id, DateTime.now)
.paginate(:page => params[:page], :per_page => Jobeet::Application::MAX_JOBS_ON_CATEGORY_PAGE)
.order("expires_at desc")
When I trying get category.id in controller I am getting error:
undefined method `id' for #
Could somebody give me any advice?
If you expect a single record you should do:
#category = Category.get_by_slug(params[:slug]).first
because .where(something) doesn't return a single record.

Convert SQL query to rails Active Record query interface

I have the following sql query and I want to map it to a rails count query:
SELECT count(*), DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) as converted_date
FROM video_logs
where user_id = 19 and question_id = 96 and dashboard = 'player_question'
GROUP BY converted_date;
How do I do this?
In rails 3:
VideoLog.select("count(*), DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) as converted_date").\
where(:user_id => 19, :question_id => 96, :dashboard => 'player_question').\
group('converted_date')
In rails 2:
VideoLog.all(:select => "count(*), DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) as converted_date",
:conditions => {:user_id => 19, :question_id => 96, :dashboard => 'player_question'},
:group => 'converted_date')

Optimise ignoring of undefined variables when building find conditions in Rails

I have a an method that retrieves Groups that are present in certain areas. Groups are given a country_id, region_id and city_id
The UI gives three select boxes to choose a country, a region from that country and then a city from that region. To find all groups in a particular city, I have this code:
#groups = Group.find(:all, :conditions => {:city_id => params[:city_id]})
This all works fine, but I also want it to find all groups in an area when the lower criteria isn't specified. For example, If a country and region are given, but not city, I'd like to find it by the region.
What I'm doing is this:
if !params[:city_id].nil?
#groups = Group.find(:all, :conditions => {:city_id => params[:city_id]})
else
if !params[:region_id].nil?
#groups = Group.find(:all, :conditions => {:region_id => params[:region_id]})
else
#groups = Group.find(:all, :conditions => {:country_id => params[:country_id]})
end
end
This works perfectly well, but it seems like it's a little inefficient. Am I doing it the best way or can I streamline a little?
One idea I had was to have a single find checking against all parameters, but I could not work out how to effectively 'ignore' parameters that were nil - my main thought was to check which ones were not set and set them to something like '*' or 'true', but that's not how SQL plays the game.
Sounds like a job for named scopes:
class Group < ActiveRecord::Base
named_scope :in_city, lambda { |city_id| {
:conditions => { :city_id => city_id }
}}
named_scope :in_region, lambda { |region_id | {
:conditions => { :region_id => region_id }
}}
named_scope :in_country, lambda { |country_id | {
:conditions => { :country_id => country_id }
}}
end
This establishes some simple scopes for restricting the Group records. Presumably you have indexed your database properly so these are quick to resolve.
The controller is much easier to implement then:
def index
#group_scope = Group
if (!params[:city_id].blank?)
#group_scope = #group_scope.in_city(params[:city_id])
elsif (!params[:region_id].blank?)
#group_scope = #group_scope.in_region(params[:region_id])
elsif (!params[:country_id].blank?)
#group_scope = #group_scope.in_country(params[:country_id])
end
#groups = #group_scope.all
end
Generally you should be testing for .blank? instead of .nil? as some form elements can send in empty results, such as a select with something akin to "All" as the default.
You could use some Ruby idioms to get something a little more succinct.
Try something like this: (untested code!)
def index
#groups = Group.find :all, :conditions => [:city_id, :region_id, :country_id].inject {} do |conditions, name|
conditions[name] = params[name] unless params[name].blank?
conditions
end
end
If every value in params is a candidate for :conditions you can just do this:
#groups = Group.all(:conditions => params.reject { |idx, val| val.nil? })
This just throws out nil values from params and uses the remaining values for conditions.
If you don't want to use all of the values in params, you have two options. You can just get rid of a bunch of redundancy in your original code:
conditions = if !params[:city_id].nil?
{ :city_id => params[:city_id] }
elsif !params[:region_id].nil?
{ :region_id => params[:region_id] }
else
{ :country_id => params[:country_id] }
end
#groups = Group.all(:conditions => conditions)
You can knock of a few more lines like this, but it sacrifices a bit of readability IMO:
conditions = if !params[:city_id].nil? then { :city_id => params[:city_id] }
elsif !params[:region_id].nil? then { :region_id => params[:region_id] }
else { :country_id => params[:country_id] }
end
Or you can do something like this:
conditions = [:city_id, :region_id, :country_id].inject({}) do |hsh, sym|
hsh[sym] = params[sym] unless params[sym].nil?
hsh
end
#groups = Group.all(:conditions => conditions)
This has the advantage that you don't need to add another condition for each symbol.