How to filter a model based on two parameters

14 views
Skip to first unread message

Christopher D.

unread,
May 8, 2012, 12:09:28 PM5/8/12
to rubyonra...@googlegroups.com
Hi I’m looking to query a Post model based on two attributes.
- the current user’s id
- a “1” in an integer attribute that I have created

I hope to show the title each one of this persons posts that have a 1 in
the integer attribute

This is what I am thinking of having

Posts Controller (I need help here, below is what I was thinking)
def selectview
@posts = Post.find( :user_id == session[:user_id], :intatt == 1)
End

Posts view
<%= @posts.each do |post| %>
<%= post.title %>
<% end %>

I am most concerned about how to code the controller, any help would be
appreciated.

--
Posted via http://www.ruby-forum.com/.

Colin Law

unread,
May 8, 2012, 12:25:37 PM5/8/12
to rubyonra...@googlegroups.com
Assuming that you have set up the relationships properly, so User
has_many posts then to get all the posts for the current user you can
just say current_user.posts, then if you want intat to be 1 also you
just say
current_user.posts.where( :itatt => 1 )
which will give you effectively an array of Post objects.

If you don't know what user has_many posts means then have a look at
the Rails Guide on ActiveRecord associations, though I strongly
suggest you work through some Rails tutorials such as
railstutorial.org, which is free to use online, before going any
further.

Colin

Christopher D.

unread,
May 8, 2012, 10:38:53 PM5/8/12
to rubyonra...@googlegroups.com
Colin!

Thanks for the help. I ended up using something similar.

@instvar = Model.where( :user_id => current_user.id, :itatt => 1 )


Again, I really appreciate the feedback

Colin Law

unread,
May 9, 2012, 2:58:52 AM5/9/12
to rubyonra...@googlegroups.com
On 9 May 2012 03:38, Christopher D. <li...@ruby-forum.com> wrote:
> Colin!
>
> Thanks for the help. I ended up using something similar.
>
>  @instvar = Model.where( :user_id => current_user.id, :itatt => 1 )

What is wrong with using current_user.posts?

Colin

>
>
> Again, I really appreciate the feedback
>
> --
> Posted via http://www.ruby-forum.com/.
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
>
Reply all
Reply to author
Forward
0 new messages