I have a rails app that works almost like a blog, and I use a tagging system to categorize the posts.
I need to add to some of the posts something similar to a "related posts" feature.
So for example if post 1 is related to post 4, at the end of the show action for post one I want to render an image of post 4 and at the same time at the end of post 4 an image of post 1.
My idea is to create a "link" model that has a HABTM relations with the post model, but I'm not sure if a "post" has many "links" trough "linkings" would be better.
Both of the ideas seem to have the same result, so which approach should I prefer?
HABTM is by nature very simple, with just a table of foreign key pairs joining models.
Typically has_many through is used when you need to add additional attributes to that join relation, and/or when you need to treat the joins as their own model.
In your case, for example, you might want the links to appear in the order that they were created. For this to happen you'd need to store the create timestamp on the relationship. For this, the simple HABTM join table is not enough, so you switch to has_many through and create a Linking model to encapsulate the join.
To continue the example, you might also make Linking a first-class resource, and have a page where you can edit/add/remove them separately from either linked Post.
Personally I've always used has_many through in the majority of cases. It just feels cleaner to me (no auto-naming table magic to accept or override, and the linking is more visible), and I find that very often, join relationships do deserve to be first class citizens.
Related
How do I associate two entries in a database that are connected through a many-to-many relationship in Rails?
I'm trying to associate Users and Issues for an issue tracker. I'm using has_and_belongs_to_many, not :through. I have a :user_id and :issue_id available to me, but there doesn't seem to be User.issues.find(id) or Issue.users.find(id) available to me. I have a route post "/", to: "home#create". I'm trying to make a create method in home_controller.rb.
From the look of it you're calling the method on the User class and not an instance.
If you want to get the issues connected to a user you need to fetch the user first:
User.find(id).issues
If you want to add a record to the association you can use the shovel method or any of the methods generated by the association macro:
User.find(id).issues << Issue.find(3)
User.find(id).issues.push(Issue.find(3))
User.find(id).issue_ids = [1, 2, 3]
Besides that you have a smattering of naming issues in your schema. Use snake_case everywhere in your database schema unless you have a good reason why you want to break the conventions and feel like explicitly configuring table and foreign key names.
I would also really question if you really want to use has_and_belongs_to_many. It should only really be used if you can't foresee that you ever will need to add additional attributes to the join table or never need to query the table directly - it seems pretty unrealistic that that would be true in an issue tracker. You want has_many through: - pretty much always.
I have a route post "/", to: "home#create". I'm trying to make a
create method in home_controller.rb.
Don't throw everything into a junk drawer controller. Think about your app in terms of resources that can be CRUD:ed and create controllers that handle just that resource. You should think about what the relation between a user and an issue is in your domain and how you can model it as an actual entity in the domain logic instead of just plumbing.
Maybe all I need to do is direct you to Rails Guides: Active Record Associations.
There is neither of these
User.issues.find(id)
Issue.users.find(id)
because when you are finding an issue or user by id, you don't use the association. Instead use these:
Issues.find(id)
Users.find(id)
Since the :id is unique this will work and should be what you want.
The only time you want to query issues or users using the association will be when you have the data for the other end of the relationship.
user = User.find(user_id)
issue = user.issues.where(id: issue_id)
Since the :id field is unique, this is the same as Issues.find(id). However if you want to get a collection of a user's issues with some other data, you can put the condition for that data in the where.
You can create an issue for a user this way:
user = User.find(user_id)
issue = User.issues.create( ... )
I have a project that is built with a tagging model to reference three different models: artist, article, event. I have associated each model to the tagging model via has_many through:. I have two problems; both related to each other:
I have 5 "default" methods that I wish to be able to call restfully from the tagging controller/model: popular, upcoming, events, articles, and artists. Each method is designed to do exactly as it's name implies. The issue lies within these methods being a query by nature. How can I maintain a consistent schema where 5 of the many taggings models I have require a special attribute (let's call it content) that should subsequently call the appropriate method?
When calling any one of the taggings models, it will return (in it's content attribute) an array of the 3 models specified earlier. Other than adding a method within each model that contains a localized description of the model and then calling upon that type method to match another hardcoded string elsewhere, is there any alternative? I don't like how the implementation I just described requires me to hardcode values. Eek.
I'm very new to Ruby on Rails, so I apologize if this is an obvious solution. However I have spent a week looking into ways to solve this compound problem that I'm trying to solve. Any input is appreciated!
As far as i unterstand you need a polymorphic association. Because tags can be applied on different models, the clue is to treat all these models in polymorphic manner by marking them as :taggable on the association to tags.
I would just use the popular acts_as_taggable_on gem for it.
I am very new to Ruby on Rails.
I am trying to set up a relationship between a user model and a model of ten different items.
My goal is to have users be able to check off items in the items model and then have the ones that have been checked off display on their profile.
I have used the Michael Hartl Ruby on Rails tutorial up to
the point of creating microposts.
Any tips on tutorials that will help me complete this would be greatly appreciated.
Thanks!
Basically, what you want is:
A User has_and_belongs_to_many :items
Also, an Item has_and_belongs_to_many :users
This is many to many relationship. Since, a user can has many items, and an item can belong to many users too. In rails, here has_and_belongs_to_many will implicitly create a table items_users which will contain id's of both, establishing the relationship.
Read more about this association here - http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association
Use checkbox tag for showing checkboxes for all the items. Documentation - http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box
Based on whatever checkboxes are checked, save the records, establishing the relationship.
Done. :)
I don't know about other tutorials, if you've completed Hatel's then you have a very very good understanding of the rails framework as a whole. I would have an items_list model. Which had a user_id foreign key to associate itself with a user. Then I could have an items model which had an items_list foreign key to associate them to a list. Then items model could have a boolean field "active" or "checked" or whatever. Using these, and the associated relations, and some scopes, you can get what you want.
Just make sure to use the includes helper when you request this data, otherwise you'll easily get a N+1 problem.
http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
I am building a blog-style application in Rails 3 where multiple users are able to post some news. After the login (which is realized with "Authlogic") the user values are stored in a own model called e.g. "UserSession". The form for the post contains title, content etc. and the username should be stored with a hidden form.
I think that the two models don't need to be related to each other (by that I mean a :has_many - :belongs_to relationship) because there isn't any further usage for that information.
Do I really not need this relation? And how could I realize the form?
For Authlogic is it important to remember that the 'UserSession' does not correspond to any database tables (i.e. you would never use a has_many or has_one 'UserSession'). I think the relationship you are looking for is:
User has many Posts
Blog belongs to User
The reason? It is always a good idea to associate a record with the 'owner' so that the owner can later modify or delete the record. I hope this helps.
I am new to rails so go easy. I have two tables that I am trying to work with here, 'post' and 'category'.
The 'post' table includes the following columns, title:string content:text category:string.
The 'category' table simply contains name:string.
The idea is that the client can manage the categories and also when adding a new post, they can select from a drop down that references their categories.
What is the best way to accomplish this?
You might want to model the category differently. The usual approach is to create a PostCategory model and controller, and use a relation from posts to PostCategory. Read up on belongs_to and the other rails associations before you get much further into this project. When you're ready to continue, take a look at formtastic, it makes handling the forms for the associations much easier to code
flyfishr64 is right, the "correct" way to do this would be to put the categories in their own model/table.
There's lots of helpers like collection_select that will take your list of categories (PostCategory.all) and make a dropdown list for you with the appropriate name to save it in a specific field.
That said, you could pull a distinct list of the entries in that column already and use that for your dropdown, but it's a lot more hassle than just making a model for the category.