Proper usage of .includes and .joins - ruby-on-rails

I have 3 models
Options:
class Option < ActiveRecord::Base
attr_accessible :key, :name
belongs_to :item_options
end
ItemOptions
class ItemOption < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :item
belongs_to :option
end
and Item:
class Item < ActiveRecord::Base
has_many :item_options
has_many :options, :through => :item_options
end
And I need my controller to return all items with their options in JSON format so i'm trying to use .includes but with no luck:
items = Item
.order('id')
.where(manufacturer)
.where('is_active')
render :json => {:data => items.offset(offset), :total => items.count}.to_json(
:include => :options
)
Result does not contain options but i see in console there are appropriate DB requests. However it does only works if i use :include inside to_json:
items = Item
.order('id')
.where(manufacturer)
.where('is_active')
render :json => {:data => items.offset(offset), :total => items.count}.to_json(
:include => :options
)
So the first question is what am i doing wrong so that .include does not work?
But i aslo have problem with working code. I need options to be joined with item_options because options just store options name, options group id and so on, when item_options keeps value for defined option for defined item. And so i'm trying to extend my code as follows:
items = Item
.order('id')
.where(manufacturer)
.where('is_active')
render :json => {:data => items.offset(offset), :total => items.count}.to_json(
:include => {
:options => {
:joins => :item_options
}
}
)
But still, i receive options not beeing joined with item_options. Why?
Also if i use joins inside optoins do i need to define has_many through in items if they loaded without additional information in item_options?
========== UPDATE:
For now i just replaced an options relation to method in Items model:
item = Item
.includes(:item_options)
.find(params[:id])
render :json => item.to_json(:methods => :options)
and in Item model:
has_many :item_options
def options
self.item_options.select('item_options.value, options.name, options.is_feature, options.root').joins('left join options on options.id = item_options.option_id')
end
Don't know, however, if this solution is optimal.

Your calling to_json on a hash and not on the model, and Hash knows nothing about includes or joins.
Try putting your json options on the model
data = items.offset(offset).as_json(include: :options)
render json: {data: data, total: items.count}
Also, I think your Option belongs_to :item_options should be Option has_many :item_options
Using :include within as_json is an instruction to the ActiveModel json serializer telling it to include data from associations in the output JSON.
ActiveModel::Serializers::JSON
(github)
The joins and includes methods are part of ActiveRecord and are used to add join conditions and perform eager loading.
ActiveRecord joins
ActiveRecord includes

Related

how to use joins to get back a single query selected elements from two tables

I have (in Rails 3.2.13):
class User < ActiveRecord::Base
has_many :app_event_login_logouts
end
class AppEventLoginLogout < ActiveRecord::Base
belongs_to :user
end
and would like to get back something like:
AppEventLoginLogoug.select("id, type, users.email").joins(:user)
basically id, type from app_event_login_logouts and email from users but this doesn't seem to be working. What would be the correct syntax?
Try out following code:
ret = User.joins(:app_event_login_logouts).select('app_event_login_logouts.id, app_event_login_logouts.type, users.email')
ret.first.id # will return app_event_login_logouts.id
ret.first.email # will return users.email
...
AppEventLoginLogoug.find(:all,
{:include => [:users],
:select => ['id', 'type', 'users.email']})
I also checked the apidoc and found something like that:
result= AppEventLoginLogoug.find(:all,
:conditions => ['condition_here'],
:joins => [:users],
:select => 'whatever_to_select'
:order => 'your.order')

Rewrite SQL query with tire

I'm trying to rewrite a query with tire.
This is the model that I have:
class User < ActiveRecord::Base
has_many :bookmarks, :dependent => :destroy
has_many :followed_venues, :through => :bookmarks, :source => :bookmarkable, :source_type => 'Venue'
end
A user can follow venues. And I need to search for venues that are followed by a certain users.
So far I've been doing it with ActiveRecord:
#user.followed_venues.where(["venues.title LIKE ?", "%"+params[:q]+"%"])
This is obviously not ideal, so I added elasticsearch to my app with tire.
How would I search for venues with tire, filtering by the user that is following them?
I'm going to post an answer to my own question.
So it's quite easy to just search venues. Standard Venue.tire.search {...} The problem is how to filter by user that follows venues. Instead of using the Venue model for searching, I decided to index bookmarks.
This is my bookmark model
class Bookmark < ActiveRecord::Base
belongs_to :bookmarkable, :polymorphic => true
def to_indexed_json
{
:title => bookmarkable.display_name,
:user_id => user_id
}.to_json
end
end
After this I have the user_id and the venue name in the index. Now search becomes as simple as this:
Bookmark.tire.search :load => {:include => 'bookmarkable'}, :page => page, :per_page => per_page do
query do
fuzzy :title => { :value => query.downcase, :min_similarity => 0.6, :prefix_length => 2}
end
filter :terms, {:bookmarkable_type => ["Venue"], :user_id => [user.id]}
end
Now this is not a complete solution. And I hope i'm even using filter :terms correctly. The result that I get back now is an array of bookmarks actually. But it's easy to load the actual venues for them, and maybe wrap it in a WillPaginate collection for better pagination on the frontend.
Any problems with this solution? How would it compare to what phoet suggested with putting user ids to the venue index?
i would create a document for each venue and then add a field with an array of all the user-ids that are following.
are you really sure, that this is a proper task for elasticsearch?
i guess it would be way easier to just search the index for the name of the venue and then look up the data you need in your relational database.

acts_as_api rails query for non related field

I've two tables which are related say A and B. A has has_many to B and B belongs_to A. However I've a field in A stored say A.account_number. And A is totally unrelated to table C which is accounts table. D has account details like addresses and other details. C has has_many relation to D and D belongs_to C. Now using acts_as_api in A and B . I wrote a big query which almost fetches every field I need except for the account and acoount details. How do I get this details using acts_as_api. I tried using calling scopes sub resource method. but it did not work. Any ideas. Please share. I'm new to rails. Here is my code.
Let's Say
A-> item_people
B-> item_people_roles
C-> people_accounts
D-> people_account_details
Class ItemPeople
class ItemPeople < ActiveRecord::Base
has_many:item_people_roles, class_name => "ItemPeopleRole", :dependent => :destroy
accepts_nested_attributes_for :item_people_roles, :allow_destroy => true, :reject_if => :all_blank
acts_as_api
api_accessible :bill_rewriting do |bill|
bill.add :account_number
bill.add :item_people_roles
end
end
Class ItemPeopleRoles
class ItemPeopleRole < ActiveRecord::Base
attr_accessor :messages
belongs_to :item_people, :class_name => "ItemPeople"
acts_as_api
api_accessible :bill_rewriting do |bill|
bill.add :item_people_id, :as => :shipper_id, :if => lambda{|u|u.role_type_code=="SHIPPER"}
bill.add :item_people_id, :as => :consignee_id, :if => lambda{|u|u.role_type_code=="CONSIGNEE"}
bill.add :item_people_id, :as => :ship_to_id, :if => lambda{|u|u.role_type_code=="SHIPTO"}
end
end
Class C People
class People < ActiveRecord::Base
# This model has account number
# account type fields
end
Class D People_Details
class PeopleDetails < ActiveRecord::Base
# This model has address1, address2, name1, name2
end
Now according to people's role there in the itempeopleroles, I need to get people and people details fields in acts_as_api of ItemPeople. Hope I'm clear now
The best way to accomplish this is via a template Proc/lambda
api_accessible :public do |template|
template.add lambda { |record,options|
# look at options, and use those to build your custom data
return [the correct data]
}, :as => :a_magic_field
end
Then in your controller, get a results set, "annotate" it, and then render it.
raw_results = Model.where(... some where conditions ....)
results = raw_results.as_api_response(:public, ... [some other options to appear in your lambda])
And finally render it:
respond_to do |format|
format.json {render :json => results, :callback => params[:callback]}
format.xml {render :xml => results}
end
With this, you can write any code you want inside your lambda to navigate your data structures, regardless of how it is laid out. How it will perform is another question....
(I can't add comments yet).
If A has A.account_number and C is the table of accounts, why don't you have associations between A and C (and maybe even A and D as well as C and D)?
My "answer" is to add those associations and then just use the proper :include syntax. I don't really see what acts_as_api is providing.

Rails has_many :through and Setting Property on Join model

Similar to this question, how do I set a property on the join model just before save in this context?
class Post < ActiveRecord::Base
has_many :post_assets
has_many :assets, :through => :post_assets
has_many :featured_images, :through => :post_assets, :class_name => "Asset", :source => :asset, :conditions => ['post_assets.context = ?', "featured"]
end
class PostAssets < ActiveRecord::Base
belongs_to :post
belongs_to :asset
# context is so we know the scope or role
# the join plays
validates_presences_of :context
end
class Asset < ActiveRecord::Base
has_many :post_assets
has_many :posts, :through => :post_assets
end
I just want to be able to do this:
#post = Post.create!(:title => "A Post")
#post.featured_images << Asset.create!(:title => "An Asset")
# ...
#post = Post.first
#featured = #post.featured_images.first
#=> #<Asset id: 1, title: "An Asset">
#featured.current_post_asset #=> #<PostAsset id: 1, context: "featured">
How would that work? I've been banging my head over it all day :).
What currently happens is when I do this:
#post.featured_images << Asset.create!(:title => "An Asset")
Then the join model PostAsset that gets created never gets a chance to set context. How do I set that context property? It looks like this:
PostAsset.first #=> #<PostAsset id: 1, context: nil>
Update:
I have created a test gem to try to isolate the problem. Is there an easier way to do this?!
This ActsAsJoinable::Core class makes it so you can have many to many relationships with a context between them in the join model. And it adds helper methods. The basic tests show basically what I'm trying to do. Any better ideas on how to do this properly?
Look at the has_many options in the ActiveRecord::Associations::ClassMethods API located here: http://rails.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001316
This is the most interesting quote:
:conditions
Specify the conditions that the associated object must meet in order to be included as a WHERE SQL fragment, such as authorized = 1. Record creations from the association are scoped if a hash is used. has_many :posts, :conditions => {:published => true} will create published posts with #blog.posts.create or #blog.posts.build.
So I believe your conditions must be specified as a hash, like so:
class Post < ActiveRecord::Base
has_many :post_assets
has_many :featured_post_assets, :conditions => { :context => 'featured' }
has_many :assets, :through => :post_assets
has_many :featured_images, :through => :featured_post_assets,
:class_name => "Asset", :source => :asset,
end
And you should also do the following:
#post.featured_images.build(:title => "An asset")
instead of:
#post.featured_images << Asset.create!(:title => "An Asset")
This should call the scoped asset build, as suggested in the quote above to add the context field to asset. It will also save both the join model object (post_asset) and the asset object to the database at the same time in one atomic transaction.

find_with_ferret , multiple model not working

I have 2 models A and B.
class A < ActiveRecord::Base
has_one :b
acts_as_ferret :fields => [:title,:description]
In a_cotroller, i wrote:
#search=A.find_with_ferret(params[:st][:text_search],:limit => :all).paginate :per_page =>10, :page=>params[:page]
The above title and description search is properly working.
class B < ActiveRecord::Base
belongs_to :a
Now,I want to perform a text search by using 3 fields; title, description(part of A) and comment(part of B). Where I want to include the comment field to perform the ferret search.Then,what other changes needed.
The documentation of find_with_ferret indicates that you simply code :store_class_name => :true to enable search over multiple models. While this is true there is a little more to it. To search multiple do the following:
#search = A.find_with_ferret(
params[:st][:text_search],
:limit => :all,
:multi => [B]
).paginate :per_page =>10, :page=>params[:page]
Notice the multi option. This is an array of the additional indexes to search.
Now to get his to work you have to rebuild your indexes after adding :store_class_name => :true to the index definitions.
class A < ActiveRecord::Base
has_one :b
acts_as_ferret :store_class_name => :true, :fields => [:title, :description]
end
OR...
You can simply include Bs fields in the index definition:
class A < ActiveRecord::Base
has_one :b
acts_as_ferret :fields => [:title, :description],
:additional_fields => [:b_content, :b_title]
def b_content
b.content
end
def b_title
b.title
end
end
This makes everything simple, but doesn't allow to search the B model independently of A.

Resources