Accessing relationship tables data in rails (using has_many :through) - ruby-on-rails

It is my first question, but I have yet to find an answer, so I hope it doesn't violate any rule.
I have a problem with a seemingly simple rails issue. I have taken the time to read about relationship models in rails (has_many :through) and came upon this example:
Exemplary model relations
In my model, I have Anthology (phyisicians), Poem(patients), and an anthology_poem relationship model (appointments). In may relationship table, I have a column, order, that indicates the position of a specific poem in a specific anthology.
The question is - How do I address said "order" column? How do I update it/read it? I imagine something like:
book.poems.first.order
which obviously doesn't work.
I'd like to be able to do it without too much hacking, because I fell in love with how simply rails handled the rest of the stuff.
Thanks in advance!

If you want to access your relationship model attribute you should call it on that model:
Appointment.where(physician: physician).pluck(:order)

Related

Ruby on Rails child with multiple parents options

I encountered against the typical case of a model (Address) and multiple models having this data (Company, Person). Let's work with these models as example, but can be generalized with any others.
Making the correct choice is important, as changing the database schema or making deep changes are not easy later.
Initially it will be one-to-one association, then we have these possibilities:
1) Use the classical normalization and put all the address data into each model requiring it. Then create an address subform for render partial into each one, and put the code behavior into a Module to be called from each model controller using it.
This could looks fine, but it has the problem that is hard to make changes, as any change in the Address data needs to be done on each model using it. Also hard to change it to a one-to-many association, if required.
2) Rails polymorphic feature. Address is a model itself, and belongs_to :addressable, polymorphic: true, then Company and Person have has_one/has_many :address/:addresses, as :addressable. Then add the polymorphic FK to Address table and it's done.
I like this solution, it is clear and with only 2 extra columns we have done it. The only contra I can think about is we rely in a framework feature, so if someday we migrate to another one, it should feature polymorphic too. Well this is not really true because we can always make the SQL manually searching by addressable_type = "type", but I think is not database design standard.
3) Join tables. One for each parent. So we have JT_Company_Address, JT_Person_Address, and we use the Rails has_one/has_many :through associations using those join tables.
I think using join tables is more database design standard, but add some extra tables.
4) Reverse the relationship, making Address the parent and each of the other a child. So each child would have a FK address_id.
I don't like much this one, as I will handle mainly companies and persons, and then look up their address if required, not the opposite, looking addresses and then loop up what it has in it. We can always use the bidiriectional association using the Rails inverse_of, but at database layer Address would be the parent one anycase.
My favorites at this moment are 2 and 3. I will probably use Rails and not move from it, so the polymorphic looks very easy and clean.
Then, what do you think, which one is the best one? Any advice is welcome.
Thanks.

How to design/model a has many relationship that has a meaningful join table?

I wasn't able to put well into words (in Question title) what I'm trying to do, so in honor of the saying that an image is worth a thousand words; In a nutshell what I'm trying to do is..
Basically, what I have is A Teacher has many Appointments and A Student has many Appointments which roughly translates to:
I'm trying to stay away from using the has_and_belongs_to_many macro, because my appointments model has some meaning(operations), for instance it has a Boolean field: confirmed.
So, I was thinking about using the has_many :through macro, and perhaps using an "Appointable" join table model? What do you guys think?
The Scenario I'm trying to code is simple;
A Student requests an Appointment with a Teacher at certain Date/Time
If Teacher is available (and wants to give lesson at that Date/Time), She confirms the Appointment.
I hope you can tell me how would you approach this problem? Is my assumption of using the has_many :through macro correct?
Thank you!
Both teachers and students could inherit from a single class e.g. Person. Then create an association between Person and Appointments. This way you keep the architecture open so that if in the future you want to add 'Parents' then they could easily be integrated and may participate in appointments.
It may not be completely straightforward how you do the joins with the children classes (Students, Parents, Teachers). It may involve polymorphic relationships which I don't particularly like. You should though get away with a single join table.
In any case, you want to design so that your system can be extended. Some extra work early on will save you a lot of work later.

Need help creating a Model and migration for Tag model for Post model (Rails)

I have a Post model and I would like to create a Tag model so that posts can have tags (more than one at a time). I want to be able to search a post's tags and search posts tagged as X.
This is what I've realized so far in order to make this work (correct me if I'm wrong):
The Tag model only needs a :name attribute and the Post model needs a :tag_list attribute)
The Post and Tag must have either has_and_belongs_to_many or many-to-many associations between them (not sure which one).
I have no idea about the view or the form or how separating tags with a coma or a space will tun into separate tags that belong to the post.
Any suggestions or insights (with examples if possible).
A few recommendations:
I think you'll need a join table as well, something like posts_tags or posts_to_tags, that
has a tag_id and a post_id.
There's a pretty good example of the difference between many-to-many and HABTM in the AR docs. In this case, I'd use the HABTM because your join table doesn't have any meaningful characteristics (unlike the example, where "Assignment" is a first-class model).
Going from comma-delimited string to separate tags should probably be done with a before_save filter or something -- not sure there's built-in behavior here.
You could also look into the tagging gems listed on Ruby Toolbox if you're not doing this for learning purposes.
You can use has_many :through association. This is one of the best solution to your situation.
There is a detailed tutorial on Rails Guide:
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

Parent Model that can only have one child in Rails?

Sorry the title is pretty unclear - I'm just not quiet sure how to phrase the question without explaining it.
I would like to record workouts with my app. I would like a Workout Table (what I'm calling the parent) that has basic information like date and sub_workout_type_id
A workout record can have either a Cardiovascular workout (One Model) or a Strength Workout (Another Model).
My thought on have 3 tables instead of just the 2 Cario Workout model and strength workout model is that I would be able to pull a feed of any type of workout, by pulling the Workout Records and then dig deeper as needed.
Perhaps there is a more ruby-ish way to do this? Because right now I don't know of a way to say has_one_model_or_the_other. Thanks!
I see two options, either you use STI (single table inheritance) : in that case you would have a single table that would be able to contain both a cardiovascular model or a strength workout, and a type. This would only work if the two models share some common characteristics.
Another solution is to write something like
has_one :cardiovascular
has_one :strength
and then use validations to enforce that only one of them is set.
Hope this helps.
As mentioned by #nathanvda, STI could be a good choice.
If you're looking to store class specific data with your models, maybe check out Modeling inheritance with Ruby/Rails ORMs to see if that answer gives you any ideas on how to model this relationship.
Note, the example there uses has_many's but a lot of the ideas are similar.

RoR: belongs_to_many relationship in Rails?

I have a Model of Key Termsthat can belong to many Articles (1 Term can be used in many articles)? so a user can add key terms used and their explanations to articles for which they are used in? what would be the best way to establish this relationship?
Thank You
You'll want to use a many-to-many relationship so you'll need to use has_and_belongs_to_many (see here). And you'll need to create an interim table for key_term_id and article_id columns named key_terms_articles to maintain the connection.
I think what you want is what's referred to as a HABTM (has and belongs to many) relationship. There's a lot of stuff out there on the topic, and it can be a bit confusing at first to grasp. Try searching for "activerecord HABTM" or "Activerecord polymorph" and that should get you started.

Resources