Nesting the resources necessary? Rails - ruby-on-rails

I have user model and boat model. User has many boats. Boat belongs to user. What i wonder is that, even though i did not nest the resources i am able to create a boat to logged in user. So my url becomes ..../boats.new2 (2 as user id) and it actually saves to user with an id number 2.
But as far as i know if i have nested resources it would become something like .../user/2/boats/1. Isn't it?.
I have not tried to #edit action any of the cases so not sure which one to use and their effects, is there any other advantages using any of them, or not nesting is wrong?

Nesting routes is not necessary in Rails. You can maintain the relationship between boats and users as long as you have the active record belongs_to and has_many methods defined in the model, along with the foreign keys in the db.
In general, you should nest resources if there is an obvious relationship between the objects, such as users and posts (or boats). It just makes more sense of your users and as an API structure.
In some cases, you might want to nest the relationship under something different, like a category name. For instance, your uri pattern could look like /sailboats/boats/1 or powerboats/boat/2. Bottom line is you should structure routes in a way that logical for the project's users and developers.

Related

How do I associate two entries in a database that are connected through a many-to-many relationship in Rails?

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( ... )

Allowing admin and users to sign in using same form (rails)

I've created 2 tables, one for users and one for admins.
I created 2 tables as they both collect different information, but I want to be able to allow a sign in using an email address and password from both the admin and user tables via the same form.
Is this possible? I've looked around and people seem to have created 1 users table and added an admin boolean, but I wanted to avoid this and I didn't want to collect unnecessary data if I didn't need to.
Any help and assistance about how to best go around this would be great.
If you are implementing something from scratch, then it is simply a matter of coding it. I think this approach has some inherent flaws and I would avoid it.
If you want to have some segregation on the model side of things, I suggest you use STI. That way there is some shared behaviour/attributes and the distinctions can be coded separately, so you have your protection.
If you have plenty of distinct attributes, I would suggest separating them from your user/admin and creating an "admin_profile" model that belongs_to :admin and a "user_profile" that belongs_to :user.
And to make coding "transparent", you can create accessors in your admin model class to get/set the profile attributes seamlessly. Say you have an is_cool attribute on the admin_profile model, but you'd like to access it as
imadmin.is_cool
You can have in your admin.rb model
has_one :admin_profile
def is_cool
self.admin_profile.is_cool
end
be careful cause the has_one relationship may return nil if there is no profile associated with the admin/user.

Nesting resources for User Comment on Event

I am trying to get better with Rails and nesting resources. A User has many Event (and vice versa) through UserEvent join table. I also want a User to Comment on an Event. So far, Event is nested under User in my resources. How would you nest Comment? Would that be nested under Event so there are two successively nested resources under User? How would that work?
I think this would be my suggested nested approach:
resources :users
resources :events do
resources :comments
end
In a many-to-many relationship, it doesn't usually make sense to nest one under the other because neither has a stronger containment relationship.
In your scenario, a user doesn't belong to one event and an event doesn't belong to one user, so having your routes represent it like that doesn't quite model the relationship. Your URLs would look like /events/1/users/2. That sort of implies that User 2 only exists in Event 1.
I think it would make sense that your User and Event are top-level resources. Comments, on the other hand, do have some ownership which makes sense to nest. More than likely, a Comment will be associated with the Event in regards to context. The User is simply the person responsible for it. Nesting comments under the user would give you easy URLs to display all the comments for a user, but I'm betting you're more likely to display all the comments for an Event. With that in mind, I would suggest nesting Comments under Events.
This also makes sense if you were to delete the user and nullify the user_id in the Comment model. You could still have a URL for the comment. If you delete the Event, the comments likely aren't useful anymore anyway, so you could simply destroy them.

Rails blog and post linking

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.

Multiple non-related models in one Rails form

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.

Resources