I have this "as_json" method in my Post model:
def as_json(options={})
super(options.merge(:include => { :comments => { :include => [:user] }, :hashtags => {}, :user => {}, :group => {} }))
end
I'd like to set a limit attribute in :comments like this:
def as_json(options={})
super(options.merge(:include => { :comments => { :include => [:user], :limit => 10 }, :hashtags => {}, :user => {}, :group => {} }))
end
but it doesn't work.
How should I proceed?
I think that you have only one possibility.
I suppouse that you have a has_many :comments association in your Post model
So you can define the next has_many association in your Post model, something like this:
has_many :ten_comments, -> { limit(10) }, class_name: "Comment", foreign_key: :post_id
And then you will be able to do this in the as_json method:
def as_json(options={})
super(options.merge(:include => { :ten_comments => { :include => [:user] }, :hashtags => {}, :user => {}, :group => {} }))
end
Sorry for posting four years later, but I hope that someone find useful your question and this answer.
Related
A bit of difficulty handling multiple children associations for posting to another rails application via Httparty gem.
From the sending application:
:parent has_many :kids
:kid has_many :schools
#parent = Parent(parent_params)
#parent = HTTParty.post("http://localhost:3001/parents/import",
:body => { :parent_id => #parent.id,
:terms_accepted => #parent.terms_accepted,
:email => #parent.email,
:kids => {
#parent.kid.school.name => #parent.kid.school_name,
#parent.kid.age => #parent.kid.age
}
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
The receiving application has the same relationship
:parent has_many :kids
the combination of array of kids and the use of singular and plural in the post syntax is throwing me off...
The console is showing:
"kids_attributes" => {"0"=>{"age"=>"10", "school_id"=>"8"}, "1"=>{"age"=>"11", "school_id"=>"9"},
Parent has_many Kids, then its expected to have an array here, try the following:
:kids => #parent.kids.map {|kid| {:school_name => kid.school.name, :age => kid.school.age }}
Im really really new to ruby/ruby on rails and was given a model class that looks like this. I just want ask why is it giving me odd number list for Hash error when I try to call Ranks.search_word("Jagger")
Im using Rails 2.3.5/ActiveRecord 2.3.5
class Ranks < ActiveRecord::Base
set_table_name 'CM_GT_RANK'
set_primary_key 'rank_id'
has_one :character_atlas, :class_name => "CharAtlas", :foreign_key => "char_id_db"
has_one :player_records, :class_name => "PlayerRecord", :foreign_key => "char_id"
default_scope :joins => :character_atlas,
:order => "rank asc"
named_scope :search_word,
lambda{ |keyword|
{
if keyword.present?
{:conditions => { :CM_CHAR_ATLAS => {:char_name => keyword }} }
else
{}
end
}
}
end
You have an additional Pair of curly brackets which are not required. Try:
named_scope :search_word, lambda{ |keyword|
if keyword.present?
{:conditions => { :CM_CHAR_ATLAS => {:char_name => keyword }} }
else
{}
end
}
I have two models linked to each other and I am trying to do an after_save, create in the model and code is as follows.
class CustomerBill < ActiveRecord::Base
after_save :updating_and_creating_ledger_items
has_many :customer_ledgers, :dependent => :destroy
def updating_and_creating_ledger_items
CustomerLedger.create(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
end
end
customer ledger model
class CustomerLedger < ActiveRecord::Base
belongs_to :customer_bill, :foreign_key => "customer_bill_id"
end
Now the problem is the program executes perfectly but the value are not been put in the database. If I check Customer ledger it is still empty.
The values are not getting stored. what seems to be the problem? Guidance towards this matter will be helpful.
Thanks in advance. :)
Add
validates_associated :customer_ledgers
In customer_bill.rb
Try
ledger = customer_ledgers.build(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
ledger.save
EDITED for to avoid Validations, use
ledger = customer_ledgers.build(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
ledger.save(:validate => false)
The CustomerLedger may be failing a validation check. Replace:
def updating_and_creating_ledger_items
CustomerLedger.create(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
end
with:
def updating_and_creating_ledger_items
ledger = customer_ledgers.build(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
ledger.save(:validate => false)
end
You're not setting the customer_bill_id in the create, change create to build as so:
customer_ledger.build(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
Using ROR 2.3.8
I have this in cities_controller.rb:
#shops = Shop.published.search params[:keyword], {
:conditions => conditions,
:star => true,
:group_by => 'city_id',
:group_function => :attr,
:page => params[:page]
}.merge(:order => 'rating_average DESC')
#cities = #shops.collect { |shop| shopy.city }
How can I tell Rails to get the rating_average from City model instead of Shop model? Because the Shop model does not have rating_average. It's actually City model that gets rated.
Thank you.
UPDATES
published namescope in Shop.rb
sphinx_scope(:published) {
{:conditions => {:status => 'published'}}
}
Indexes in Shop.rb
define_index do
indexes city.name, :as => :name, :sortable => true
indexes city.duration, :as => :duration
indexes city.status, :as => :status
#has city.budget, :as => :budget
#has city(:created_at), :as => :created_at
has city(:rating_average), :as => :rating_average
has city_id
end
UPDATES 2
class City < ActiveRecord::Base
has_many :shops, :dependent => :destroy
...
end
You should use joins to acheive this:
#shops = Shop.published.search params[:keyword], {
:conditions => conditions,
:star => true,
:group_by => :city_id,
:group_function => :attr,
:page => params[:page]
}.merge(:order => :rating_average,
:sort_mode => :desc)
You should also add cities. or shops. before columns to specify which table's column.
In my Rails project I'm using Formtastic to manage my forms. I have a model, Tags, with a column, "group". The group column is just a simple hardcoded way to organize my tags. I will post my Tag model class so you can see how it's organized
class Tag < ActiveRecord::Base
class Group
BRAND = 1
SEASON = 2
OCCASION = 3
CONDITION = 4
SUBCATEGORY = 5
end
has_many :taggings, :dependent => :destroy
has_many :plaggs, :through => :taggings
has_many :monitorings, :as => :monitorizable
validates_presence_of :name, :group
validates_uniqueness_of :name, :case_sensitive => false
def self.brands(options = {})
self.all({ :conditions => { :group => Group::BRAND } }.merge(options))
end
def self.seasons(options = {})
self.all({ :conditions => { :group => Group::SEASON } }.merge(options))
end
def self.occasions(options = {})
self.all({ :conditions => { :group => Group::OCCASION } }.merge(options))
end
def self.conditions(options = {})
self.all({ :conditions => { :group => Group::CONDITION } }.merge(options))
end
def self.subcategories(options = {})
self.all({ :conditions => { :group => Group::SUBCATEGORY } }.merge(options))
end
def self.non_brands(options = {})
self.all({ :conditions => [ "`group` != ? AND `group` != ?", Tag::Group::SUBCATEGORY, Tag::Group::BRAND] }.merge(options))
end
end
My goal is to use Formtastic to provide a grouped multiselect box, grouped by the column, "group" with the tags that are returned from the non_brands method. I have tried the following:
= f.input :tags, :required => false, :as => :select, :input_html => { :multiple => true }, :collection => tags, :selected => sel_tags, :group_by => :group, :prompt => false
But I receive the following error:
(undefined method `klass' for
nil:NilClass)
Any ideas where I'm going wrong?
Thanks for looking :]
I'm not sure we support :group_by with a custom :collection. In fact, that who part of the code was a messy contribution. So, try omitting the :collection for starters, and see where you end up. If there's a bug with Formtastic, please add an issue on Github.
I'd first move your Group class out of this file, and just inherit from where you want, or use a Module in this class. This is the preferred way of getting methods an constants into a class and staying organized.