i want to display all posts in Post table with say id=5 ......
controller
user_controller.rb
class UsersController < ApplicationController
# other methods are also present...
def profile
uid=session[:userid] #session contains userid,it is stored in uid....Eg:5
#post=Post.find_by_userid(uid) #Display all posts with userid=5 in Post table.
end
end
view
profile.html.erb
<h1>In Profile</h1>
<%=session[:test]%>
<% #post.each do |p|%>
<%= p.title%>
<%= p.body%>
<%= p.tag%>
<%end%>
when i execute i get an error like....
Showing /Users/Vineeth/QA4/app/views/users/profile.html.erb where line #3 raised:undefined method `each' for #
Please help me fix the error......thanks.
Post.find_by_userid(uid) is same as Post.where(:userid => uid).first, return only one record.
You should use Post.where(:userid => uid)
You're using Post.find_by_user(uid) which is not something you can iterate over. It only returns a single record.
Use something that returns a collection, like Post.where(:userid => uid)
Related
I'm learning RoR by building my first app (yay!). I gotta a question thought as rails guides do not cover this topic:
How to render unique results on #show to a user without storing any data in a model?
Steps I want to take:
Create a basic index view with a form_tag that will allow user to submit a link (string) and click submit button
Write Service Objects that will allow me to parse that link and create a response I want user to see
I want to write a #show method in a separate controller that will allow me to display all the data. (I also want to parse my params[:link] in that method using Service Objects.
I want to finally display this data in a table in #show view (probably I need to create a unique #show/[:id] for each user?
Here's what my app looks like at the moment (more or less):
Static Controller (just to render index.html.erb with a form)
class StaticController < ApplicationController
def index
end
end
Static Index view (yup, parsing imgur link here)
<h1>Hello Rails!</h1>
<%= form_tag("/images", method: "post") do %>
<p>
<%= label_tag(:imgur_link) %><br>
<%= text_field_tag(:imgur) %>
</p>
<p>
<%= submit_tag("Get my cards") %>
</p>
<% end %>
Images Controller (where all the magic SHOULD happen)
class ImagesController < ApplicationController
def show
#collection = params[:imgur_link]
#service1 = service1.new(*args).call
#service2 = service2.new(*args).call
...
end
end
Images Show view
Empty as I'm stuck with the Images controller at the moment.
Any help would be more than appreciated.
Thanks!
There is no reason you should put something into storage just in order to display it. If you get to a point when you have the results in your controller, you could just pass them to view in some #variable
As I see, you have set up the form for step 1. If you also have routes.rb call 'images#show' for POST /images, then you will have params[:imgur_link] available in your show action. This should do:
# config/routes.rb
YourApplication.routes.draw do
# ...
post '/images' => 'images#show'
end
Now you have to somehow process that link. Since I don't know what your results should be, I'm going to assume that you have two classes, Service1 and Service2, both of which accept an URL and return collection of results, and both collections hold the elements of the same class. Then you can leave only unique results for your show view, like this:
# app/controllers/images_controller.rb
class ImagesController < ApplicationController
def show
link = params[:imgur_link]
results1 = Service1.new(link).results
results2 = Service2.new(link).results
#results = (results1 + results2).uniq
end
end
Then you can do something with #results in your show view. E.g.
# app/views/images/show.html.erb
<% #results.each do |result| %>
<%= result.inspect %>
<% end %>
I'm building a Rails app where I have individual entries called films. I would like to display the latest entry's link on the homepage (separate controller) and I'm struggling to make it work.
My films_controller.rb is as follows (excerpt):
def show
#film = Film.find(params[:id])
end
My home_controller.rb only has the following:
def index
end
And my view file (index.html.erb) has the following:
<%= link_to #film.last.filmTitle, film_path(#film) %>
I'm getting the following error:
Couldn't find Film with 'id'=#<Film::ActiveRecord_Relation:0x007fc93f2d1fd0>
With the #film.find(params[:id]) highlighted.
Thanks!
The last method:
Find the last record (or last N records if a parameter is supplied). If no order is defined it will order by primary key.
source
You can add a #last_film instance variable in your index controller and use it in the view.
def index
#films = Film.all
#last_film = Film.last
end
and in your index.html.erb
<%= link_to #last_film.filmTitle, film_path(#last_film) %>
The index method need something, currently, it didn't connect with ActiveRecord like model or table, that's why
Couldn't find Film with 'id'=#<Film::ActiveRecord_Relation:0x007fc93f2d1fd0>
So if you need to show recent posts in the index then you could something like this
def index
#films = Film.limit(10).order(created_at: :desc) #=> or you can use id
end
it will show last 10 records, for this in the index.html.erb like this
<% #films.each do |film| %>
<%= link_to film.filmTitle, film_path(film) %>
<% end %>
In the other hand if you need to show only one post which is the last then you should modify this query like this like limit(10) to limit(1) or you can use use the last method like this
def index
#film = Film.last
#or
##films = Film.limit(1).order(created_at: :desc) #=> or you can use id
end
if you use this #film = Film.last then your index file will like this
<%= link_to #film.filmTitle, film_path(#film) %>
otherwise, you need to use each method which describes before.
I have a controller which looks something like this:
class EventController < ApplicationController
def index
...
#events = Event.where(['eventdate < ?', DateTime.now]).order("eventdate")
...
end
end
And my model defines the following relationship:
class Event < ActiveRecord::Base
...
has_many :match_items, dependent: :destroy
...
end
I am now trying to access the event_items linked to the events defined in the the instance variable #event in my view as follows:
<h2>Your Events</h2>
<% #events.each do |event| %>
</br><span>
<%= event.eventdate.to_formatted_s(:rfc822) %>
<%= event.event_items.event_comment %>
</span>
<% end %>
the event.event_items.event_comment line throws an error: undefined method 'event_comment' for []:ActiveRecord::Relation
Why can't I not access event_comment as a method?
If I just use event.event_items the line doesn't display an error and shows the whole event_items array with all it's content displayed in my view.
So i thought maybe I can just access the event_commentas part of the array through using:
<%= event.event_items.event_comment[i] %> #where i is the index of event_comment in the array
But this then doesn't return anything in my display.
Any suggestions on how I can access the attribute event_comment stored in my event_items db table? Any help is very much appreciated!
The reason you are getting that error is because event.event_items returns a ActiveRecord::Relation and not an instance of EventComment. Try using:
event.event_items.first.event_comment
I'm trying to list a user's wanted ads in their show page when they access /users/:id.
In my controller I have:
def show
#user = User.find(params[:id])
#wanted_ads = WantedAd.where(:user_id => params[:id])
And in my show.html.erb I have:
<%= #wanted_ads %>
Binding.pry says #wanted_ads is nil. On the actual page I get #<ActiveRecord::Relation:0x007fa3b5a93408>. This is seemingly a simple thing I'm trying to do -- what am I missing?
The where function returns a ActiveRecord::Relation.
So, you can call first to get the first element, last to get the last one or all to get all elements stored in an array called #wanted_ads.
#wanted_ads = WantedAd.where(:user_id => params[:id]).all
You can then go through this array and choose the attributes you want to pass to the view for each element.
Just a tip:
You should have in your User model an ActiveRecord relation, like this:
has_many :wanted_ads
And in your WantedAd model, like this:
belongs_to :user
And with this, you have a relation of one-to-may.
Then, you can do this:
def show
#user = User.includes(:wanted_ads).find(params[:id])
end
And then, in your view:
<% #user.wanted_ads.each do |wanted_ad| %>
<%# do something %>
<% end %>
where returns a collection of objects, not just a single object. So depending on what's returned you'll want to either call first to get the single instance that ought to return, or call each to iterate over the wanted ads and display them on your page.
You're seeing an instance of ActiveRecord::Relation in pry because of the underlying query mechanism that lazy loads the results. More details can be found here.
Assuming your #wanted_ads is not nil and you want to loop through all the wanted ads...
<% #wanted_ads.each do |wanted_ad| %>
<%= wanted_ad.some_attribute_of_wanted_ad %>
<% end %>
I would also suggest you be aware of SQL injection with the following code in your controller.
#wanted_ads = WantedAd.where(:user_id => params[:id])
As it should be
#wanted_ads = WantedAd.where(":user_id => ?", params[:id])
I have a users table. It contains a field "user_type".
I added the following scope stmts to the user.rb file:
scope :uemployee, where(:user_type => 'employee')
scope :uclient, where(:user_type => 'client')
scope :ucontractor, where(:user_type => 'contractor')
I created a view and I would like it to list he employees.
Here is the code I'm trying to use:
<% #users.uemployee.each do |user| %>
But, I get "undefined method `uemployee' for nil:NilClass"
What am I doing wrong?
Thanks
Looks like you wanted to do this:
<% User.uemployee.each do |user| %>
But this is considered to be a bad practice. You have to prepare you data in a controller and a view just cycles through it:
# in a controller's action
#users = User.uemployee
#in a view
<% #users.uemployee.each do |user| %>
But even this isn't the best approach. If you create the file views/users/_user.html.erb which shows the info about a particular user (current user will be available as a simple user variable, without the #) then you can simply write:
# in a view
<%= render #users %>
# remember, #users variable was set in your controller
then Rails will cycle through all the users "inside" the #users variable and show them one-by-one.
Your #users collection is nil