Jay
Jay

Reputation: 63

Filtering database outputs rails

I'm a little lost on this, so I have the activity feeds gem and the devise gem.

I want to have the ability to list all the posts made by a specified user

Controller

 def userstory
 @userstory = Story.where(params[:user_id])
 end

View

<% @userstories = Story.where(:user_ud) %>

<% @userstories.each do |story| %>

I also think my routes are wrong

 match '/stories/userstory/:user_id',     to: 'stories#userstory',       via: 'get'
resources :stories, :only =>[:show]

Upvotes: 1

Views: 49

Answers (2)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33470

Usually you handle params in Rails with forms, if you don't perform such action (fill a form, send it) you won't be able to deal with them. If you try to print in your view the current value of your params[:user_id] maybe you'll get nil, that's why when you try to find a Story through the id which in this case is nil then you get some response.

Try specifying your @stories within your controller and in the corresponding method and then use it in your view, maybe like:

# app/controllers/stories_controller.rb
def some_method
  @stories = Story.find_by_id(params[:user_id])
  ...

Just to mention, as far as I know, all the dynamic methods except for find_by_... and find_by_...! are deprecated since the Rails 4 version, so maybe you'd like to use find_by or where instead (see reference).

Seeing your routes then I assume you're in '/stories/userstory/id' in your navigator, and you click on some story to show it, then you need to use the method show in your StoriesController and this way to find such story through the params[:user_id].

Upvotes: 1

Greg Navis
Greg Navis

Reputation: 2934

First, you need to ensure that stories has a user_id column pointing to users. Second, you need to properly define associations:

class Story < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :stories
end

Then in your controller add:

# I'm assuming this is index on a controller.
def index
  @stories = current_user.stories
end

You should be able to reference @stories in a view:

<%= @stories.each do |story| %>
  <!-- RENDER story HERE -->
<% end %>

Upvotes: 2

Related Questions