Rails has_and_belongs_to_many query - ruby-on-rails

I have the following database schema in my rails 4 application
Users >---Tags_users---< Tags >---Posts_tags---< Posts
given the currently logged in user, what is the best way for me to get all of the posts (from all users) that match there tags the tags that they are interested in.

You can pass an array to Model#where to get an array of posts with the choosed criteria.
def show_by_tags
#posts = Post.all
array_of_tags.each do |tag|
#posts.where(tag_name: tag)
end
end

Related

How to access variables in model

I am trying to get access to a property contained inside my user object.
My user model has_many: posts. In the controller how would i gain access to these posts? Would i create a method in the model?
def posts
#posts = Post.find(User_id: params[:id])
end
or can i directly access the posts for the user. User.posts Since i am currently residing in the controller, is the controller aware of the currently selected model? Or do i have to pull the information again?
You can query the database for all the posts with a specific user_id, like this:
#posts = Post.where(user_id: params[:id])
Alternatively, you can find the user first and then fetch all posts associated with that user, like this:
user = User.find(params[:id])
#posts = user.posts
Assuming your id in params is the id of your user, you can use user = User.find(params[:id]) to get the user and #posts = user.posts to get all the posts of this user.
So, it is not about where you are, It is about what you are calling.
I'm sure you are familiar with relationships...
When you have relationships, it means that you can get to one relation from the other through whatever association exists between them.
If I am my father's son, then you can get me directly by checking my father's children. ( you don't necessarily have to get all children in the village first )
So, bringing all my story above together, with the association between your Post and User, you can always call user.posts (user being an instance of User) and post.user ( with post being an instance of Post)
The Ruby on Rails guides have a section on associations, which is what you want. It's here: http://guides.rubyonrails.org/association_basics.html
In a nutshell, because you have added an association in your user model to a number of post records, Rails will build a helper method in your user model called posts. You can use that to access all the posts associated with that user.
When you create a post, the post record needs to have a column called user_id. This will provide the 'physical' link between the user and post models. You can access the posts from a user like so:
user.posts each do |post|
# do something with post.content
end
To get posts that match some criteria in the posts collection you can query like this:
posts = user.posts.where(:something => 'matches criteria')
If you know there's only one post that matches the criteria, you can do this:
post = user.posts.where(:something => 'matches criteria').first
The post model also needs a belongs_to :user association. (The belongs_to will generate a helper method called user in the post model which you can then use to access the user record from the post.) For example:
user_email = post.user.email
The user record does not require a post_id column since Rails knows that user.post refers to the post table and automagically generates a query using user_id.
Anyway, the guide I linked to above will give you all the information you need and more too.

Get all records that have an associated record

A Post has_many Tags. Each tag record has a name, like "fashion" or "business".
How can I get all posts that have the tag with name "fashion"?
# Get all posts
#posts = Post.all
# Get the filter tag
#filter_tag = Tag.find_by_name(params[:filter_name])
Ok so now we have all posts, and now I just want the #posts that have the #filter_tag. What should I do?
I could loop through each post, and check if it has the filter tag. If so, add it to an array. I'm sure Rails ActiveRecord has a better method though.
If you have your associations set up correctly then
#filter_tag_posts = #filter_tag.posts

ElasticSearch in Rails using Tire Gem on Arrays

I am trying out Tire gem for my Demo Rails app to implement ElasticSearch.
So, here are my models associations :-
A User belongs to many UserGroups. And Every UserGroup has many Post associated with it.
So, this is what I do to show all the posts for a User in posts_controller.rb
def index
#user_groups = current_user.user_groups
for group in #user_groups
for p in group.posts
#posts = #posts.to_a.push p
end
end
end
Now, I want to add search functionality to it. A User may be able to search for a Post from all the Post that are visible to him.
So, I have two questions which are connected to each other.
Q1. How, do I add the search functionality by using the Tire gem for the User so that the user may search from the Posts that are visible to him ?
Tire allows to directly search on a model using
#posts = Post.search(params[:query])
But, I want to search from an array.
Q2. And Secondly, Is my approach correct, by first storing the concerned Posts in an array and then use Tire to search from that array ?

ActiveRecord help: Where tags include

I cant seem to find a way to do this. Some guidance would be great!
I'm building a blog like site with posts and posts contain tags. The tags and posts are held together by a join table. I can access them via post.tags.
Im trying to put together a search to display all posts containing a certain tag.
After trying for awhile this is the best I came up with:
def tag
tag = Tag.find_by_title(params[:id])
p = Post.page(params[:page]).per_page(7).all
#posts = Array.new
p.each do |p|
if p.tags.include? (tag)
#posts << p
end
end
This works all except the pagination. Im thinking there has got to be a simple where clause to simplify this?
Thanks!
Edit:
Here is my join table
The next method should return the array of post tagged with the tag :
#posts = Post.includes(:tags).where('tags.id' => tag.id)
You just have to keep the first line of your method and add the line above after.
Notice that to make it working you should have defined the relationships between your post and tag in your model with an has_and_belongs_to_many.

How do I only show items that belong to a certain user (using restful_authentication)?

I have a web application with users and their documents. Each user can have many documents:
user.rb:
has_many :documents
document.rb:
belongs_to :user
document_controller.rb:
def index
#documents = Document.find(:all)
end
I am using the restful_authentication plugin. Here is my question: How do I get the controller to only show documents that belongs to each user? Right now it shows all the documents for all the users.
I am using the latest version of Rails.
You set a relationship in your User class to your Document class. This will automatically add a method to your User objects that returns a list of all documents related to a particular user:
def index
#documents = #current_user.documents
end
See the documentation for other automatically added methods.
Try this:
def index
#documents = Document.where(:user_id => current_user.id)
end
def index
#documents = Document.find(:all, :conditions => {:user_id => session[:user_id]})
end
Take a look here in the rails API in the Association Join Models section.
However be aware Restful authentication won't control access in order to limit the users to only their own records particularly with restful routes. They can still view other users' records by entering values in the urls once they are logged in.
For that you might want to look into Restful ACL

Resources