I'm new to rails and am done setting up my login system. However, I want someone to be able to make a new blog post and attach it to their account when logged in. How can I attach a post to their user_id as well as list all their previous posts?
Define a model posts ( should have column name user_id )
model Post < ActiveRecord::Base
belongs_to :user
end
In user Model
model User < ActiveRecord::Base
has_many :posts
end
With the above defined associations user_id will be a foriegn key to User model so you can
get all posts by user something like below
User.find(id).posts
There are quite a few different approaches, but John Nunemaker's user_stamp gem is pretty straightforward and simple to get running.
https://github.com/jnunemaker/user_stamp
Just add a creator_id and updater_id to your table, a single line in your ApplicationController, and it'll do the rest!
You can associate models with each other by following this guide on rails associations. One solution for you might be:
class Post < ActiveRecord::Base
end
class User < ActiveRecord::Base
has_many :posts
end
You just have to make sure that your posts table has a column called user_id. Assuming your user table is called users. this will set up a one to many association between users and posts. From a User instance you will be able to do user.posts and get a list of the associated posts for that user.
The guide is much better at explaining this stuff and it's worth your while to read the whole thing--even the parts you don't need right now.
Related
I have a single users table through Devise. Branching off this table are 3 other models (author.rb, seller.rb and buyer.rb) with each having a one to one relationship with the main Users table.
The reason for this is each have some unique attributes and I want to keep the main Users table tidy. I am using active admin and want to avoid redundant fields when registering a new user.
Currently I am using enums to assign user roles:
enum role: [:author, :sellers, :buyers]
The problem is when I set a role it works in the sense that I can restrict what a user sees based on that role however there is a big issue I have below.
The problem:
I want to be able to register an Author. Everything good so far. But I also want to be able to register a Buyer and then associate that buyer with the author as two different users. At the moment a user is becoming both at the same time through nested forms in active admin I used which is not what I want. I want a user to be a buyer and the other user to be an author.
Maybe I don't have my relationships set up correctly for this? Or it could be a problem in active admin?
class Author < ActiveRecord::Base
belongs_to :user
end
class Buyer < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_one :author
has_one :buyer
end
Basically I want to be able to register two different users and after that associate them and I don't know how to do this. Any advice much appreciated.
I need help fixing this relationship in Rails 4.1,
User Model Relationship
has_and_belongs_to_many :blogs, join_table: 'blogs_users'
has_many :posts, through: :blogs
Blog Model Relationship
has_many :posts
Post Model Relationship
belongs_to :blog
belongs_to :user
Issue?
The following, in rails c, works - how ever the user id is not passed in:
User.find_by_x(x).blogs.find_by_x(x).post.create(x)
The post is created for a user who has said blog attached, but because of how this type of chaining works, only the blog_id is passed to the post and not the user_id Its crucial I have both blog and user id.
So I thought, why not just create the post through the user object and pass in the blog id.
User.find_by_x(x).posts.create(x, blog_id: y) # Where y represents a blog the user is associated with.
Well that's all good and stuff accept I get this error:
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly: Cannot modify association 'User#posts' because it goes through more than one other association.
I believe the issue is the fact that I have a join table and I am saying has_many :posts, through: blogs Most people might assume that "just remove the through part." How ever I need this type of relationship where a user can have many blogs and blogs can belong to many users and posts belongs to a blog and to a user but a user can have many posts ....
So is there a way to fix this to keep my concept or ...
the way you are creating posts does not make much sense.
this would be the usual way of doing it:
blog = current_user.blogs.find(params[:blog_id])
post = blog.posts.create(params[:post])
respond_with(post)
The correct solution to this issue is a couple of things, one I needed to make sure that the realtionship between blog and user was the same as user and blog so in the blogs model I added:
has_and_belongs_to_many :users, join_table: 'blogs_users'
Then I needed to create posts at a post level, not a user level. So instead of, #user.posts.create() I need to do Post.create(blog_id: x, user_id: x) and then #user.posts
will work properly (assuming the user has 2 blogs with one post in each you'll get back both posts)
I would like my User to be associated with specific Email's, when they receive them.
In this way, I can look up an array of what emails they have received.
Originally, I was thinking of just creating a string field for the User table, and adding the unique ID to the array..
User.find(x).received_emails << Email.find(x).id
But there may be a better way to do this with associating models.
Recommendations?
You should check this link out:
Rails association guide
It sounds like you're talking about a one to many sort of thing. If you use the association mechanism you'll get all the behavior you want, basically for free.
class Email < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :received_emails, :class_name => 'Email'
end
User.find(x).received_emails << Email.find(y)
This approach would require adding a user_id column to the Email table.
You probably want to change this to a many-to-many association by adding a join table such as user_emails with a UserEmail model. That table would have user_id and email_id columns.
I am working on an application where a user has the ability to leave feedback on another user. Currently, I already have an implemented user model.
Is this considered a self referential association?
This seems a bit wierd to me (how to set it up through Active Record Associations).
How would I go about setting this association up, what type of association is it? Anything I need to watch out for while going about this (tips, suggestions, errors that may come up)?
According to Answers Below Would This be the Way?
(one to many between users and ratings and one to one between ratings and user)
class User < ActiveRecord::Base
has_many :ratings
end
class Ratings < ActiveRecord::Base
belongs_to :user
end
This may not be in Rails/Active Record terms but ORM generic.
I would probably implement this by having a Feedback or Review model and your User model would have one-to-many Feedback/Reviews and the Feedback/Review would have a one-to-one relationship with the User who created it.
EDIT: Response to question update...
You can have an User object on the Ratings model that is the author. My rails experience is minimal but I believe your Ratings model would look like this.
class Ratings < ActiveRecord::Base
belongs_to :user
has_one :user
end
Im creating my own blog managing app in rails (for experimental purposes).... What would the best way to get this done?
I have posts and categories.
I want to have a dropdown of categories for the user to select one when they create a new post.
Now, each user will have different privileges so not all categories should appear for all users....
Right now Im at the point where I can create posts and choose which category I want... I havent added any filter per user support....
please help me on where should I go now??
First you will need to implement authentication and authorization. There are many good Rails tutorials on these subjects so I won't go into more detail here.
At this point you will have models for User, Post, and Category. You need a list per-user of authorized categories. A naive model:
class User < ActiveRecord::Base
has_and_belongs_to_many :categories
end
But that is misleading, because a user isn't actually "in" any categories. You probably want something like a join model like so:
class UserCategoryAuthorization < ActiveRecord::Base
belongs_to :user
belongs_to :category
// More fields here; possibly:
// belongs_to :authorized_by, :class_name => 'User'
end
class User < ActiveRecord::Base
has_many :user_category_authorizations
has_many :authorized_categories,
:through => :user_category_authorizations,
:source => :category
end
To start with I would give Users a has_many categories relationship(Which you could turn into its own model object at some point if this idea gets more complicated..or now if it already makes sense) and then assuming you already have log in functionality you can ask the logged in user for its categories and populate the drop down appropriately.
If this is a security issue rather than just convenience then you will need to validate the chosen category is in the users categories when the form is submitted back to the server.
If you don't already have logins I believe there are several rails plug-ins that attempt to help you get this functionality quickly.