I'm trying to put some code in a partial from my show page in /events. The code works fine when I use it in my show page, but when i extract it to a partial I'm getting a No Method Error
undefined method `event' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_PaperTrail_Version:0x007f4368823a68>
versions/_version.html.erb
<% cache version do %>
<div class="feed-item">
<h4>
<%= link_to version.item.name, version.item %>
<small>
<%= version.event + "d" %> by <%= link_to User.find(version.whodunnit).username, User.find(version.whodunnit) %>
</small>
</h4>
<ul class="list-unstyled">
<% version.changeset.each do |data| %>
<li>
<strong><%= data[0].capitalize %>:</strong>
<% if data[1][0].present? %><p class="red">- <%= data[1][0] %></p><% end %>
<p class="green">+ <%= data[1][1] %></p>
</li>
<% end %>
</ul>
</div>
<% end %>
show.html.erb
<%= render :partial => '/versions/version', :object => #versions %>
events controller
def show
#versions = #event.versions
end
events model
has_paper_trail
Any idea how i could put my code in a partial instead of having it inside my show view? Thanks.
EDIT:
I still get a No Method Error
undefined method `item' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_PaperTrail_Version:0x007f43688ee1a0>
events_controller.rb
before_action :set_event, only: [:show, :update, :destroy]
def set_event
#event = Event.find(params[:id])
end
Do you have defined the #eventvariable in the eventscontroller?
The #event.versions method has to be called on an actual event object.
For example
def show
#event = Event.find(1)
#versions = #event.versions
end
Related
I am trying to create a simple app where you find games from an API via a search bar. I am using the Giant Bomb API gem (https://github.com/games-directory/api-giantbomb). The gem seems to be working since I can call things via the console. However, I am not quite sure how to display results or if there are problems with my search method (likely).
Here is my controller for Games:
class GamesController < ApplicationController
//Display search results
def index
#games = Game.all.order('created_at DESC')
#games = #games.search(params[:query]) if params[:query].present?
end
//Searches through API and redirects to results on index.
def search
#games = GiantBomb::Search.new().query(params[:query]).resources('game').limit(5).fetch
redirect_to index_path
end
private
def game_params
params.require(:game).permit(:name)
end
end
My search bar code on my home page:
<div class="search-font"><h1>Build your Collection</h1></div>
<div class="container">
<div class="row">
<div class="col-md-12">
<%= form_tag search_path class: "row", method: :get do %>
<div class="col-12 col-sm pr-sm-0">
<%= text_field_tag :game,
params[:game],
class: "form-control input-lg",
id: "typed-text" %>
</div>
<div class="input-group-btn ml-3">
<%= submit_tag "Search", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
</div>
And my index.html.erb where it is supposed to spit out the game names.
<ul>
<% #games.each do |game| %>
<li><%= game.name %></li>
<% end %>
</ul>
The search bar redirects but nothing is posted. In my console I can do search.query('Mario') then search.fetch to print out the results, but I am not sure how to use this function in my controller correctly.
[edit] Here are my routes as well.
Rails.application.routes.draw do
devise_for :users
resources :games
root to: 'pages#home'
get '/search', to: 'games#search', as: :search
get '/games', to: 'games#index', as: :index
end
redirect_to creates a new request, you need to use render as in...
render 'index'
That way you can use your #games variable in the view
I'm having trouble with using link_to in Ruby on Rails. I'm making a blog like application which displays a feed of all user posts and allows users to click posts to view/edit them.
This is my _feed partial, which is used to render all the posts of a user.
<% if #feed_items.any? %>
<% #feed_items.in_groups_of(3, false).each do |feeds| %>
<div class="row">
<% feeds.each do |feed| %>
<div class="col-md-4">
<ol class="posts">
<%= link_to render feed , edit_post_path(feed) %>
</ol>
</div>
<% end %>
</div>
<% end %>
<% end %>
The line <%= link_to render feed , edit_post_path(feed) %> is what is throwing errors. I'm just not 100% certain how to write a link_to which also renders the feed. I've tried a lot of variations and nothing works. The error I get as it is currently written is: undefined method `keys' for "/posts/160/edit":String
This is my Posts controller, which I wrote after this error occurred in an attempt to fix it. I'm not sure if any of this is even necessary:
class PostsController < ApplicationController
before_action :find_note, only: [:show, :edit]
def edit
end
def show
end
private
def find_note
#post = Post.find(params[:id])
end
I'm sure my problem is super basic but I'm having trouble figuring out how to solve it. Any help is appreciated!
Use block to render a partial inside of a link:
<%= link_to edit_post_path(feed) do %>
<%= render feed %>
<% end %>
So in my tutors_controller.rb this is my index action
def index
#tutor = Tutor.all
#tutor = #tutor.fees_search(params[:fees_search]) if params[:fees_search].present?
end
and in my index.html.erb this is the view
<div class='container'>
<%= form_tag(tutors_path, method: :get) do %>
<%= label_tag 'fees_search', 'Max Fees' %>
<%= select_tag 'fees_search', options_for_select((10..50).step(10)) %>
<%= submit_tag 'Filter' %>
<% end %>
<% #tutor.each do |tutor| %>
<% unless tutor.admin? %>
<div class='row' id='tutor-listing'>
<div class='col-xs-4'>
<%= image_tag(tutor.profile.avatar.url, :class => "img-rounded" ) if tutor.profile.avatar? %>
</div>
<div class='col-xs-8'>
<h3><%= link_to tutor.full_name, tutor_path(tutor) %></h3>
<% unless tutor.subjects.nil? %>
<% tutor.subjects.each do |subs| %>
<span class='badge'id='tutor-listing-badge'>
<%= link_to subs.name, subject_path(subs) %>
</span>
<% end %>
<% end %>
<% unless current_tutor %>
<%= button_to "Shortlist Tutor", add_to_cart_path(tutor.id), :method => :post %>
<% end %>
</div>
</div>
<% end %>
<% end %>
</div>
So i understand that when the index view first renders, #tutor would simply be Tutor.all so it renders each individual tutor perfectly.
After trying to filter it though, i start receiving errors. The exact error is NoMethodError in Tutors#indexand the highlighted line is <% unless tutor.admin? %>
profile.rb model
class Profile < ActiveRecord::Base
belongs_to :tutor
scope :fees_to, -> (fees_to) { where("fees_to <= ?", "#{fees_to}") }
end
tutor.rb model
class Tutor < ActiveRecord::Base
has_one :profile, dependent: :destroy
def self.fees_search(n)
#profile = Profile.fees_to(n)
if #profile.empty?
return Tutor.none
else
#profile.each do |y|
y.tutor
end
end
end
end
I get that now my #tutor instance variable has obviously changed. But how do i go about resolving this problem? Should i be rendering a partial instead? Obviously my index action in my controller could be "better" also but i'm quite confused now as to what i should be doing.
Would appreciate any advice! Thank you!
#profile.each do |y|
y.tutor
end
Seems to be a problem. All the other outcomes are a Tutor.something scope, whereas this will return the last tutor only. Change each to map to get an array of Tutors instead.
I've got this working now quite accidentally, but I don't understand what causes it to break when I explicitly specify what partials are to be used for rendering the resource/s. Can anyone explain it?
The index template for my Posts controller contained the following line, which was giving me an error:
<%= render partial: 'posts', collection: #posts %>
The error (in my browser) said:
NoMethodError in Posts#index
Showing /Users/applebum/Sites/rails_projects/eventful2/app/views/posts/_posts.html.erb where line #1 raised:
undefined method `any?' for #<Post:0x000001064b21f0>
Extracted source (around line #1):
1: <% if posts.any? %>
2: <div id="posts">
3: <% posts.each do |post| %>
4: <%= render partial: "posts/post", locals: { post: post } %>
Changing the problem line to
<%= render #posts %>
made the error disappear and the posts appear (displayed nicely in markup from the appropriate partials) as I had wanted and expected them to.
Here's my _posts.html.erb partial:
<% if posts.any? %>
<div id="posts">
<% posts.each do |post| %>
<%= render partial: "posts/post", locals: { post: post } %>
<% # render :partial => "comments/comments", :collection => post.comments %>
<% end %>
</div>
<% end %>
And the _post.html.erb partial it's referring to, if that matters:
<div class="post" id="post_<%= "#{post.id}" %>">
<div class="post_inner">
<%= link_to avatar_for(post.user, size: "small"), post.user.profile %>
<div class="post_body">
<div class="user-tools">
<% if can? :destroy, post %>
<%= link_to '<i class="fi-x"></i>'.html_safe, post, :method => :delete, remote: true, :class => "delete", :confirm => "Are you sure you want to delete this post?", :title => post.content %>
<% end %>
</div>
<h5 class="username">
<%= link_to post.user.name, post.user.profile %>
<span class="timestamp">• <%= time_ago_in_words(post.created_at) %> ago</span>
</h5>
<div class="content">
<%= post.content %>
</div>
<ul class="foot">
<li>Like<li>
<li>Share</li>
</ul>
</div>
</div>
</div>
And the relevant bits from the controller:
class PostsController < ApplicationController
respond_to :html, :js # Allow for AJAX requests as well as HTML ones.
before_filter :load_postable
load_and_authorize_resource
def index
#post = Post.new
#posts = #postable.posts
end
private #################
def load_postable
klass = [User, Event].detect { |c| params["#{c.name.underscore}_id"] } # Look for which one of these there's a ***_id parameter name for
#postable = klass.find(params["#{klass.name.underscore}_id"]) # Call find on that, passing in that parameter. eg Event.find(1)
end
Can anyone explain to me what's going on here? I couldn't find anything in the Layouts and Rendering guide at rubyonrails.org.
Thanks!
Your error comes from assuming :collection and #posts mean the same thing when rendering. From Rails Docs (point 3.4.5):
Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection
So, if you use that, for each post, you will be doing post.any? which fails as any? isn't defined for a single post.
From the same docs, you should check if render returns Nil to see if the collection is empty:
<h1>Posts</h1>
<%= render(#posts) || "There are no posts." %>
PD: Use the partial to render only one post, not all of them.
GL & HF.
I am trying to ensure that each job has the correct link when a user clicks on it.
The issue I am having is that I keep getting the error Couldn't find job without an ID.
In my view I have the following code:
<% #jobs.group_by{|x| x.created_at.strftime("%d %b. %Y")}.each do |date,jobs_on_that_date| %>
<section class="date"><%= date %></section>
<section id="top-job">
<% jobs_on_that_date.each do |job| %>
<section id="job-wrapper">
<%= link_to url_with_protocol(#link.job_url), :target => '_blank' do %>
<section id="job">
<%= job.title %> - <%= job.company %>
<%= job.salary %>
<%= job.location %>
<%= job.job_type %>
</section>
</section>
<% end %>
<% end %>
</section>
<% end %>
In my controller I am creating an object called #link as follows:
def index
#user = current_user
#jobs = Job.where('created_at > ?', 30.days.ago).reverse
#link = Job.find(params[:id])
end
Finally I have the following Routes setup.
JobappV2::Application.routes.draw do
devise_for :users
resources :jobs
resources :users do
resources :jobs
end
root :to => 'jobs#index'
end
If I use #link = Job.find(2) this works but every job ends up with the link input by the job with id 2.
Thanks in advance for any help!
what is params[:id]?
I suspect that if you do raise params[:id].inspect in your controller, you will find it's nil. Besides, what's the point in creating #link? just put job.job_url in your view instead of #link.job_url