Challenging Rails Question with Form Based on Existing Resources - ruby-on-rails

You have a set of related models created through a scaffold e.g. a house, which has many rooms, which each have many windows, which each has a selection of locks.
These resources are already full of data i.e. someone has entered all the information, such as: a room called 'kitchen' has various windows associated with it and these windows each have five different locks associated with them.
Someone comes along and says:
Can you create a form that lets someone create a new project where they can select the different rooms, windows and then specify the locks that they would like for that project? (these are already in the system, nothing new to add, just the associations to a new project)
This sounds like a nested form but I have wasted a lot of time trying to solve this - there are many levels of nesting, which make this tricky. Any suggestions?

session based solution
With such deeply nested models select box on the front end wouldn't be enough...
Assuming this, you may want to create a current_house who's id live in a session (just like current_user works).
Once you have your current_house add different items by navigating to your list of items view and clicking on the add_to link :
# house_controller.rb
def add_to
current_house.polymorphic_items << Kitchen.find(params[:id])
redirect_to :back
end
But there are many approaches to this session based solution which sort of implements a cart/order system. You may want to add a current_item to add stuff in each leaf of your tree aka room of your house.
E.G after clicking on the kitchen you just added :
before_filter :set_current_item
def add_to
current_item.windows << Window.find(id)
end
current_item beeing polymorphic : a living room, a bathroom etc.
But how you implement that precisely depends on your Domain Model....
As a rule of thumb regarding nested forms I'd follow rails guidance for routes : don't go deeper than one level or you'll end up in a mess.

Yes this is a nested form. Railscasts nested forms is a great place to start.
If everything is already in the system you probably just want select boxes so they can select what they want. Also check out the .build method. If you have multiple levels of nesting you can also manually set the association by passing in the foreign key yourself.

I think you can model this with a single level of nested attributes, given the models below (based on Windows/Locks pre-existing and a room just needing to mix and match them into a set of windows with given locks):
class House < ActiveRecord::Base
has_many :rooms
end
class Room < ActiveRecord::Base
belongs_to :house
has_many :window_configs
end
class WindowConfig < ActiveRecord::Base
belongs_to :room
belongs_to :window
belongs_to :lock
end
class Lock < ActiveRecord::Base
has_many :window_configs
end
class Window < ActiveRecord::Base
has_many :window_configs
end
... based on that model setup, you could have a single house form that you dynamically add child 'room' definitions to that each have a name and a collection of window_configs which have two select boxes for each one (choose a window definition and then a lock definition). Because you're dynamically adding multiple rooms with multiple windows, you'd need some JS to populate new form elements, but it could all live in a single nested form.
form_for :house do |form|
# Dynamically add a Room form for each room you want with js
form.fields_for :room do |room_attributes|
room_attributes.text_field :name
# Dynamically add window_config forms on Room w/ JS
room_attributes.fields_for :window_config do |window_attributes|
window_attributes.select :window_id, Window.all
window_attributes.select :lock_id, Lock.all

Related

Ruby on rails - nested forms with has_many through

Basically, I want to write a web-based curation tool for clinical conditions (disease) and their underlying genetics. Say, I have a clinical condition (class: Phenotype), and I have "mutations"(class: Genotype) that belong to that condition - either individually (i.e. a given mutation is directly causing this condition) or as a group (two or more mutations together cause the condition). Each condition can have one or more of such groups (i.e. may be cause by different mutations or groups of mutations). So I figured I need to create a grouping class (class: GenotypeGroup) to make that association. What I cannot figure out is how to do the form... First, I would want to enter a phenotype with some description. I then would like to use the "show" view to add a new genotype_group to that phenotype (Add new genotype group). This would have to create, implicitly (since it is basically only a cross-reference table) the genotype_group and one or more genotypes which it links to the phenotype entry.
Right now, I have:
class Phenotype
has_many :genotype_groups
has_many :genotypes, through: :genotype_groups
accepts_nested_attributes_for :genotype_groups
end
class GenotypeGroup
belongs_to :phenotype
has_many :genotypes
accepts_nested_attributes_for :genotypes
end
class Genotype
belongs_to :genotype
end
And zero idea how this would work in terms of nested forms. If anyone has a helpful web resources (been googling for > 1hour now, but apparently don't even know what the thing I am trying to do is called..) - that would be great!
Cheers,
M
Turns out I was missing two things:
a) When nesting the genotype object, I need to add a "Genotype.new" to the nested form element:
<% f.fields_for :genotypes, Genotype.new do |gt| %>
something_here
<% end %>
b) I had to declare which variables should be carried (i.e. are permitted) by the params object in the respective controller(s) so that I could pass those values between the classes during the nested object creation.

Associate two already existing objects using Has And Belongs To Many

I'm making an App in Rails to show anime, these animes has and belongs to many languages, so I made a HABTM association:
class Anime < ActiveRecord::Base
has_and_belongs_to_many :languages
end
class Language < ActiveRecord::Base
has_and_belongs_to_many :animes
end
Now I don't know how can I make associations between them, I've created many Languages' records to use them, for example, Language with ID 1 is English, Language with ID 2 is Spanish, etc... And I want to just make the associations between an anime and a language, ie, if I want to say that the Anime with ID 1 it's available in Spanish only, then in the table animes_languages I want to create the record with values anime_id: 1 and language_id: 2 and nothing more, but I belive that if I execute the command Anime.find(1).languages.create it will not use an already existing language, it will create a new language, but the only thing I want is to make associations between already existing animes with already existing languages, so, How can I do this? Should I make a model for the table animes_language?
It's confusing for me cause when I created that table as specified here enter link description here, I created the table without ID, it only have the fields anime_id and language_id.
Just to be safe I will back it up.
First you migrate your tables to remove already existing association to one or the other reference (i.e. if language already have many animes, etc).
Then you need to create a migration to create the associative table.
rails g migration CreateJoinTableAnimeLanguage anime language
Then the association pointers in your models should work properly.
class Anime < ActiveRecord::Base
has_and_belongs_to_many :languages
end
class Language < ActiveRecord::Base
has_and_belongs_to_many :animes
end
At which point whenever you want to associate one to the other already existing:
Anime.find(1).languages << Language.find(1)
Experience would recommend against trying to do this in seperate steps.
I'd say find what gets created the most, I'd guess Anime, then find a way to choose or create a language using:
class AnimeController < ApplicationController
def create
#anime = Anime.new(anime_params)
#success = #anime.save
end
private
def anime_params
params.require(:anime).permit(:stuff, :languages => [:id, :or_stuff])
end
end
Should be as simple as
anime = Anime.find(1)
language = Language.find(1)
anime.languages << language
And that will create the join record in between the two

Minimizing instance variables in views

I'm seeking brainstorming input for a Rails design issue I've run across.
I have simple Book reviews feature. There's a Book class, a User class, and a UserBook class (a.k.a., reviews and ratings).
class User < ActiveRecord::Base
has_many :user_books
end
# (book_id, user_id, review data...)
class UserBook < ActiveRecord::Base
belongs_to :user
belongs_to :book
end
In the corresponding book controller for the "show" book action, I need to load the book data along with the set of book reviews. I also need to find out whether the current user (if there is one) has contributed to those reviews.
I'm currently running two queries, Book.where(...) and UserBook.where(...), and placing the results into two separate objects passed on to the view. Now, while I could run a third query to find whether the user is among those reviews (on UserBook), I'd prefer to pull that from the #reviews result set. But do I do that in the controller, or in the view?
Also worth noting is that in the view I have to draw Add vs Update review buttons accordingly, with their corresponding ajax URLs. So I'd prefer to know it before I start looping through a result set.
If I detect this in the controller though, I'll need three instance variables passed in, which I understand is considered distasteful in Rails land. Not sure how to avoid this.
Suggestions appreciated.
This smells like a case for has_many through, which is designed for cases where you want to access the data of a third table through an intermediate table (in this case, UserBook)
Great explanation of has_many :through here
Might look something like this:
class User < ActiveRecord::Base
has_many :user_books
has_many :users, through: :books
end
Then you can simply call
#user = User.find(x)
#user.user_books` # (perhaps aliased as `User.find(x).reviews`)
and
#user.books
to get a list of all books associated with the User.
This way, you can gain access to all of the information you need for a particular user with a single #user instance variable.
PS - You'll want to take a look at the concept of Eager loading, which will prevent you from making extraneous database calls while fetching all of this information.

ActiveAdmin automatically loading full association table

I'm working on a project that uses ActiveAdmin for its administration backend.
I have two models, a Book model which has_many Products. When I try to access the products index view in ActiveAdmin, it seems to try to load the full books table into memory (there are about 1.5 million books in my database). CPU usage goes up to 100% and memory usage spikes to gigabytes.
Turning on mysql logging confirms that this is what happens when this view is called:
17 Query SELECT `books`.* FROM `books`
As far as I can tell this happens before any attempt to load the products.
To figure out this issue I stripped the models down to their bare bones:
class Product < ActiveRecord::Base
belongs_to :book
end
class Book < ActiveRecord::Base
has_many :products
end
I also reduced the AA definition to its most basic form:
ActiveAdmin.register Product do
end
Is this normal for ActiveAdmin? It doesn't seem like desirable behavior.
For anyone dealing with this same issue, I finally traced it to the automatically generated sidebar in ActiveAdmin. This includes a search field that includes a select box for all associated records.
If you have an associated table with over a million records like I do AA will happily attempt to insert the entire table into the select box.
The answer was to include some custom filters in the AA definition for products like so:
ActiveAdmin.register Product do
filter :title
end
That way the association won't be included (unless you specify it yourself.)
A better approach now is to use remove_filter for the particular attribute or relationship:
Or you can also remove a filter and still preserve the default
filters:
preserve_default_filters!
remove_filter :id
https://activeadmin.info/3-index-pages.html

How to decide which action to use

I'm very new to web-development (I feel like all my posts lately have started that way) and becoming, with time, less new to rails. I'm at a point where I can do a sizeable amount of the things required for my job but there's one nagging problem I keep running into:
How do I decide if which action I should use for a given task? index, show, new, edit, create, update or destroy?
destroy is pretty obvious and I can loosely divide the rest into two buckets with index/show in one and new/edit/create in the other. But how do I decide which one to use or if I should build one of my own?
Some general guidelines or links to further reading would be very beneficial for me.
Here is how I think of these 7 RESTful Controller actions. Take, for example, a Person resource. The corresponding PeopleController would contain the following actions:
index: List a set of people (maybe with some optional conditions).
show: Load a single, previously created Person with the intention of viewing. The corresponding View is usually "read-only."
new: Setup or build an new instance of a Person. It hasn't been saved yet, just setup. The corresponding View is usually some type of form where the user can enter attribute values for this new Person. When this form is submitted, Rails sends it to the "create" action.
create: Save the Person that was setup using the "new" action.
edit: Retrieve a previously created Person with the intention of changing its attributes. The changes have not been made or submitted yet. The corresponding View is usually a form that Rails will submit to the "update" action.
update: Save the changes made when editing a previously created Person.
destroy: Well, as you guessed, destroy or delete a previously created Person.
Of course there is some debate as to whether these 7 actions are sufficient for all controllers, but in my experience they tend to do the job with few exceptions. Adding other actions is usually a sign of needing an additional type of resource.
For example, say you have an HR application full of Person resources you are just dying to hire. In order to accomplish this, you may be tempted to create a "hire" action (i.e., /people/456/hire). However, a more RESTful approach would instead consider this the "creation" of an Employment resource. Something like the following:
class Person < ActiveRecord::Base
has_many :employments
has_many :employers, :class_name => 'Company', :through => :employments, :source => :company
end
class Employement < ActiveRecord::Base
belongs_to :person
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :employments
has_many :employees, :class_name => 'Person', :through => :employments, :source => :person
end
The EmploymentsController's create action would then be used.
Okay, this is getting long. Don't be afraid to setup a lot of different resources (and you probably won't use all 7 Controller actions for each of these). It pays off in the long run and helps you stick to these 7 basic RESTful actions.
You can name your actions whatever you want. Generally, by Rails convention, index is the default one, show shows one item, list shows many, new and edit start editing a new or old item, and create and update will save them, respectively. destroy will kill an item, as you guessed. But all these are just conventions: you can name your action yellowtail if that's what you want to do.

Resources