get items from database using rails - ruby-on-rails

i'm starting to learn rails, and i'm creating a little website, but i don't know how can i get a list from database.
i have 3 tables:
user
pills
dependent
class User < ActiveRecord::Base
has_many:user_dependents
end
class Dependent < ActiveRecord::Base
has_many:pill_dependents
has_many:user_dependents
end
class PillDependent < ActiveRecord::Base
belongs_to:pill
belongs_to:dependent
end
How can i get the list of Pills, from all the dependents connected with the user?

If I'm understandig correctly, you want to define a transitions table connecting Users and Dependents. In rails you can map this relation automatically by using has_many :through. After you ran the migrations, you can access the Users from a Dependent by running for example:
dependent = Dependent.first
users = dependent.users
And the other way arround
user = Users.first
dependents = user.dependents
Rails does involve a lot of magic. It is necessary to learn about this magic by some tutorials. Otherwise there remain things you just won't get.
I'd recommend rails for zombies from codeschool. They're very good in explaining the magic.

Related

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.

Rails user configurable migrations through views

I'm making a business administration Rails app.
Is there any info available on how I can enable admin users to add a new field to a table? Behind the scenes this would generate and run the migration and I guess some metaprogramming to include the field in the index, show and _form.html.rb views..
You can't run migrations like that, but you can solve the problem.
The answer is here
403-dynamic-forms
If you con't have a subscription, get one. Railscasts is gold for any rails developer
Basically you make a table in the database for the fields to a model.
For instance
class Product
has_many :product_fields
end
class ProductFields
belongs_to :product
end

Backbone.js, Rails 3 and ActiveRecord Relations

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.

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.

Resources