Backbone.js, Rails 3 and ActiveRecord Relations - ruby-on-rails

Before I start, let me excuse myself for asking such a basic question, but I really didn't find any suitable information.
So, I have two ActiveRecord Models, Managers and Orders:
class Manager < ActiveRecord::Base
attr_accessible ...
has_many :orders
class Order < ActiveRecord::Base
belongs_to :manager
I have a backbone collection, which perfectly fetches managers. But what I don't get is how to get my manager's orders. Is there a solution for that or should I handle this manually?

If you want to fetch a list of managers, with each manager having a list of their orders in JSON format, I highly recommend the rabl gem. It makes it very easy to set this up and if needed customize what's included in the JSON, whether you're using Backbone, KnockoutJS or something else on the front end.

Related

How to access has_many through relationship possible in rails?

How can I access my related records?
class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories
class Categories < ActiveRecord::Base
has_many :post_categories
has_many :post, through: :post_categories
class PostCategories < ActiveRecord::Base
belongs_to :post
belongs_to :category
PostCategories table has id, posts_id, and categories_id columns.
id | posts_id | categories_id
1. | 2 | 3
2. | 2 | 4
What I want is: to get posts related to a category. like: all Posts where in x category.
Yep, this is an easy one.
one_or_more_categories = # Category.find... or Category.where...
posts = Post.joins(:categories).where(category: one_or_more_categories)
Rails is clever enough to take either a model or a query that would find some data and turn that into an efficient appropriate query, that might be a subquery. Trying things out in the Rails console (bundle exec rails c) is a good way to see the generated SQL and better understand what's going on.
(EDIT: As another answer points out, if you've already retrieved a specific Category instance then you can just reference category.posts and work with that relationship directly, including chaining in .order, .limit and so-on).
Another way to write it 'lower level' would be:
Post.joins(:categories).where(category: {id: one_or_more_category_ids})
...which is in essence what Rails will be doing under the hood when given an ActiveRecord model instance or an ActiveRecord::Relation. If you already knew the e.g. category "name", or some other indexed text column that you could search on, then you'd adjust the above accordingly:
Post.joins(:categories).where(category: {name: name_of_category})
The pattern of joins and where taking a Hash where the join table name is used as a key with values nested under there can be taken as deep as you like (e.g. if categories had-many subcategories) and you can find more about that in Rails Guides or appropriate web searches. The only gotcha is the tortuous singular/plural stuff, which Rails uses to try and make things more "English-y" but sometimes - as in this case - just creates an additional cognitive burden of needing to remember which parts should be singular and which plural.
Not sure if this answers it but in ActiveRecord your Post will have direct access to your Category model and vice versa. So you could identify the category you want the posts from in a variable or an instance variable, and query #specific_category.posts. If you are doing this in your controller, you could even do it in before_action filter. If you are using it in serializers its not much different.
You could also create a scope in your Post model and use either active record or raw SQL to query specific parameters.
You also have an error in your Category model. Has many is always plural so it would be has_many :posts, through: :post_categories
Get the category object and you can directly fetch the related posts. Please see the following
category = Category.find(id)
posts = category.posts
Since you have already configured the has_many_through relation, rails will fetch post records related the category.

Rails association, nested forms and STI

Here are my simplified models
class Offer < ApplicationRecord
has_many :rooms
end
class Room < ApplicationRecord
belongs_to :offer
end
class Kitchen < Room
end
I'm using STI for Kitchen, cause it seemed the right way to express what I wanted to do (I'm probably wrong).
I want to be able to create an Offer with Rooms in it. I have 'regular' rooms that are instances of Room directly, and more specified rooms such as a Kitchen which can have an extra attribute.
I'm using cocoon to create nested form, it works great to create an offer and add regular rooms. But how can I add kitchens ?
Maybe it's an architecture issue more than an implementation issue. How would you manage to do something like this ?
One solution would be to add JSONB column data to your rooms table. Then you can use jsonb_accessor gem to elegantly manage STI.
I assume you have type column already so you can do something like:
Kitchen.create(offer_id: 1, name: "Great Kitchen", description: "It is great!")
Notice: description would be attribute of JSONB data column. In addition you can create indices for JSONB attributes and even do queries. From my experience, you want to keep JSONB as place to store additional info and less for heavy queries.
I hope this helps.

What is the preferred way to implement settings in a Ruby on Rails 3 application?

I'm building a Rails 3 application that will have user-specific settings (looks, functionality, etc) and I was seeking some simple advice on whats the preferred way of actually implementing settings.
Do you prefer to have a dedicated model for this stuff? Are hashes acceptable to store in a database field? Do you prefer cookies or sessions over the database? Is an STI object best?
Maybe list some pros or cons to each different method if you can.
Thanks.
i've same situation like you, user specific setting. In my apps i prefer creating a model to store user's configuration i've User model and User_configuration model, where the relationship is one-to-one.
class User < ActiveRecord::Base
has_one :user_configuration
end
class UserConfiguration < ActiveRecord::Base
belongs_to :user, :dependent => :destroy
end
Or if you prefer using Hash and store it to database is possible to mark your field as serialize
class User < ActiveRecord::Base
serialize :preferences, Hash
end
you can see it at http://api.rubyonrails.org/classes/ActiveRecord/Base.html
pros:
- so far i've doesn't have any problem, it easy to maintenance
cons:
- request more table in database
May be it could help you thanks.
If you want some structured solution you can either have a look at:
Configurable Engine
or rails-settings

rails polymorphic association naming suggestion

I have a container class I need to name, today it is called "EnrollmentApplication". It is a container of one type of application.
I've decided to push some of the business logic specific to different types of applications into a delegate associated with the application via a polymorphic relationship, to allow support for different types of applications. I'm struggling with a good name for the class and the relationship:
today:
EnrollmentApplication and applicationable
It's no longer just an application, but a collection of tasks and steps , kind of a workflow.
Portfolio and portfoliable....
ApplicationContainer and containable....
thanks
Joel
If the name of your class is called Enrollment then the following could work:
class Enrollment < ActiveRecord::Base
has_many :enrollment_applications
has_many :enrollments, :through => :enrollment_applications
end
Then you need your join table:
class EnrollmentApplication < Active Record::Base
belongs_to :enrollment
end
I really don't know if this will work because rails might complain about only having one id. I'm gonna try this when I get home to see if you can do this because I am actually setting up and app where user has many users. Anyway, keep us posted on your progress.

How many classes is too many? Rails STI

I am working on a very large Rails application. We initially did not use much inheritance, but we have had some eye opening experiences from a consultant and are looking to refactor some of our models.
We have the following pattern a lot in our application:
class Project < ActiveRecord::Base
has_many :graph_settings
end
class GraphType < ActiveRecord::Base
has_many :graph_settings
#graph type specific settings (units, labels, etc) stored in DB and very infrequently updated.
end
class GraphSetting < ActiveRecord::Base
belongs_to :graph_type
belongs_to :project
# Project implementation of graph type specific settings (y_min, y_max) also stored in db.
end
This also results in a ton of conditionals in views, helpers and in the GraphSetting model itself. None of this is good.
A simple refactor where we get rid of GraphType in favor of using a structure more like this:
class Graph < ActiveRecord::Base
belongs_to :project
# Generic methods and settings
end
class SpecificGraph < Graph
# Default methods and settings hard coded
# Project implementation specific details stored in db.
end
Now this makes perfect sense to me, eases testing, removes conditionals, and makes later internationalization easier. However we only have 15 to 30 graphs.
We have a very similar model (to complicated to use as an example) with close to probably 100 different 'types', and could potentially double that. They would all have relationships and methods they inheritated, some would need to override more methods then others. It seems like the perfect use, but that many just seems like a lot.
Is 200 STI classes to many? Is there another pattern we should look at?
Thanks for any wisdom and I will answer any questions.
If the differences are just in the behavior of the class, then I assume it shouldn't be a problem, and this is a good candidate for STI. (Mind you, I've never tried this with so many subclasses.)
But, if your 200 STI classes each have some unique attributes, you would need a lot of extra database columns in the master table which would be NULL, 99.5% of the time. This could be very inefficient.
To create something like "multiple table inheritance", what I've done before with success was to use a little metaprogramming to associate other tables for the details unique to each class:
class SpecificGraph < Graph
include SpecificGraphDetail::MTI
end
class SpecificGraphDetail < ActiveRecord::Base
module MTI
def self.included(base)
base.class_eval do
has_one :specific_graph_detail, :foreign_key => 'graph_id', :dependent => :destroy
delegate :extra_column, :extra_column=, :to => :specific_graph_detail
end
end
end
end
The delegation means you can access the associated detail fields as if they were directly on the model instead of going through the specific_graph_detail association, and for all intents and purposes it "looks" like these are just extra columns.
You have to trade off the situations where you need to join these extra detail tables against just having the extra columns in the master table. That will decide whether to use STI or a solution using associated tables, such as my solution above.

Resources