I have an action in my PostsController named 'tagged', which I want to return all posts tagged with whatever term.
In my routes.rb I have the following (at the top):
map.connect 'posts/tagged/:tag', { :controller => 'posts', :action => 'tagged', :tag => /[a-z\-]+/ }
Yet navigating to posts/tagged/yes returns a RecordNotFound error:
Couldn't find Post without an ID
In my tagged.html.erb file, I'll eventually be using the find_tagged_with method from acts_as_taggable_on_steroids, but for now I've put a simple Post.find(:all) to eliminate the possibility of error.
It seems like my map.connect is being overridden, and the same error occurs even if I comment the whole of the routes.rb file out except my new line.
Ok, because you can comment out the default routes that means your problem is not in your routes at all. It's that your tagged action in the posts controller probably has something like this.
def tagged
#post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #post }
end
end
Or perhaps if you spent a little more time it looks like this:
def tagged
#post = Post.find(params[:tagged])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #post }
end
end
Where as what you want is this:
def tagged
#post = Post.find(:all, :conditions => {:tagged => params[:tagged]})
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #post }
end
end
Anyway, you should be writing functional tests for this stuff and not testing in the browser.
Why not add a RESTful route for the "tagged" action?
map.resources :posts, :member => { :tagged => :put }
Related
I have a Rails 3.0 application which features a simple voting mechanism that adds a count to a number of down votes. I've set up a PUT route in routes.rb and created a method in my controller to handle it. The down vote link itself renders properly, but on clicking it gives me a Routing Error No route matches "/venues/18/down_vote" error.
Here's my controller code:
def down_vote
#venue = Venue.find(params[:id])
respond_to do |format|
if #venue.update_attribute(:mon_closed_accuracy_downvotes => #venue.mon_closed_accuracy_downvotes + 1)
format.html { redirect_to(:back, :flash => { :success => "Shenanigans were successfully called on #{ #venue.name }'s closing time." }) }
format.xml { head :ok }
else
format.html { render :action => 'show' }
format.xml { render :xml => #venue.errors, :status => :unprocessable_entity }
end
end
end
Here's my route code for the down_vote route:
resources :venues do
put 'down_vote', :on => :member
end
View code (inside a partial for a list of venues):
<%= link_to 'Incorrect?', down_vote_venue_path(venue), :method => :put %>
Again, the view itself renders fine, and the link renders as expected:
Incorrect?
Any ideas?
Sounds like you've got a problem with your javascript. Are you including the proper files? What does your layout look like?
This should have been a relatively simple one but I must be making a mistake with my routes or something. I want to return an active record as json based on an id. So heres what I have and in my eyes it should have worked.
The route:
match '/repository/infoid/(.:id)(.:format)' =>'repo#infoID', :via =>:get
The def within the controller
def infoID
puts (params[:id])
#specificObject = myObject.find_by_id(params[:id])
respond_to do |format|
format.xml{
render :xml =>
{
:returnedObject => #specificObject
}
}
end
end
Why is it that when I go to my address of http://127.0.0.1:3008/repository/infoid/1.xml
I get no route found for /infoid/1.xml
get '/repository/infoid/:id' => 'repo#infoID'
little refacrtoring for controller
def infoID
#specificObject = MyObject.find(params[:id])
respond_to do |format|
format.html{}
format.xml{
render :xml => #specificObject
}
end
end
I am really confused about Ruby on Rails REST routing. Even though I have specified that after the success it should go to the confirm action it goes to the show action and pass the ID=confirm.
def create
#article = Article.new(params[:article])
respond_to do |format|
if #article.save
format.html { redirect_to :action => "confirm" }
else
format.html { render :action => "new" }
end
end
end
The error I get is the following:
ActiveRecord::RecordNotFound in ArticlesController#show
Couldn't find Article with ID=confirm
Rails.root: /Projects/highoncoding
Application Trace | Framework Trace | Full Trace
app/controllers/articles_controller.rb:31:in `show'
UPDATE 1:
Here is my Route.rb file:
resources :articles
get "articles/confirm"
# config/routes.rb
MyApp::Application.routes.draw do
resources :articles do
member do
get 'confirm'
end
end
end
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def create
#article = Article.new(params[:article])
respond_to do |format|
if #article.save
# use a named route here
format.html { redirect_to confirm_article_url(#article) }
else
format.html { render :action => "new" }
end
end
end
end
you'll need to add the route so it looks like
match 'articles/confirm/', :controller => 'article', :action => 'confirm'
resources :articles
you need to have the :id in there or it will think that confirm is an id which is why you are seeing the error ID=confirm. make sure also that this is the first route. (at least before the resources for the articles controller.
You should probably add the confirm route directly in your routes file.
match 'articles/confirm' => 'articles#confirm'
resources only work for create/update/destroy/etc.
I am new to rails so could use some help here. I have followed several tutorials to create a blog with comments and even some of the AJAX bells and whistles and I am stuck on something that I hope is easy. The default display for both blogs and comments is to list the oldest first. How do I reverse that to show the most recent entries and the most recent comments at the top. Don't really know if this is a function of the controller or model. I have done some customization so here is the code for the controller .rb files if it helps.
COMMENTS CONTROLLER
class CommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.create!(params[:comment])
respond_to do |format|
format.html { redirect_to #post}
format.js
end
end
end
POSTS CONTROLLER
class PostsController < ApplicationController
before_filter :authenticate, :except => [:index, :show]
# GET /posts
# GET /posts.xml
def index
#posts = Post.all(:include => :comments)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #posts }
format.json { render :json => #posts }
format.atom
end
end
# GET /posts/1
# GET /posts/1.xml
def show
#post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #post }
end
end
# GET /posts/new
# GET /posts/new.xml
def new
#post = Post.new
respond_to do |format|
format.html { redirect_to #post}
format.js
end
end
# GET /posts/1/edit
def edit
#post = Post.find(params[:id])
end
# POST /posts
# POST /posts.xml
def create
#post = Post.new(params[:post])
respond_to do |format|
if #post.save
flash[:notice] = 'Post was successfully created.'
format.html { redirect_to(#post) }
format.xml { render :xml => #post, :status => :created, :location => #post }
else
format.html { render :action => "new" }
format.xml { render :xml => #post.errors, :status => :unprocessable_entity }
end
end
end
# PUT /posts/1
# PUT /posts/1.xml
def update
#post = Post.find(params[:id])
respond_to do |format|
if #post.update_attributes(params[:post])
flash[:notice] = 'Post was successfully updated.'
format.html { redirect_to(#post) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #post.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.xml
def destroy
#post = Post.find(params[:id])
#post.destroy
respond_to do |format|
format.html { redirect_to(posts_url) }
format.xml { head :ok }
end
end
private
def authenticate
authenticate_or_request_with_http_basic do |name, password|
name == "admin" && password == "secret"
end
end
end
As jtbandes pointed out, to reverse the posts in the index, you'd change the line in your index action to read:
#posts = Post.all(:include => :comments, :order => "created_at DESC")
In order to reverse the listing of your comments, there are two possibilities.
Option 1: In your post model you can declare your relationship like so:
class Post < ActiveRecord::Base
has_many :comments, :order => "created_at DESC"
end
Option 2: In your index view, simply reverse the array of each post's comments before displaying them:
<% #posts.each do |post| %>
<%= render :partial => post %>
<%= render :partial => post.comments.reverse %>
<% end %>
The options have different use cases. In option 1, you're saying that throughout your entire application, any time you refer to the comments on a post, those comments should be retrieved from the database in the specified order. You're sort of saying that this is an intrinsic property of comments in your application - posts have many comments, which are by default ordered newest first.
In option 2, you're simply reversing the comments in the index page before they're rendered. They were still retrieved in the original order (oldest first) from the database, and they'll still appear in that order anywhere else you access the comments of a post in your application.
If you're looking for a more generic way to reverse the order of the .each method, Rails has the .reverse_each method. Like so:
<% #posts.reverse_each do |post| %>
<%= render :partial => post %>
<%= render :partial => post.comments.reverse %>
<% end %>
#posts = Post.find(:all, :include => :comments, :order => "published_at DESC")
It looks like you can reverse the order using find: something like Post.find(:all, :order => "created_at DESC"). The same should apply to comments.
.reverse_each method bumping with will_paginate
here is the solution
#posts = Post.all.paginate(:order => "created_at DESC",:page => params[:page],:per_page => 5)
try use: reverse_order
Client.where("orders_count > 10").order(:name).reverse_order
this will execute the SQL:
SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC
If no ordering clause is specified in the query, the reverse_order orders by the primary key in reverse order.
Client.where("orders_count > 10").reverse_order
which will execute:
SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC
http://edgeguides.rubyonrails.org/active_record_querying.html#reorder
Simple RoR question...I am learning ROR and am making a simple voting app. The candidates are listed in a table and have upvote/downvote links next to their name. I am trying to make it so all the user does is click the link, the vote count is updated, and they are redirected to the initial page. I am not using scaffolding. For some reason this action is not doing anything close to what I want:
def upvote
#name = Name.find(params[:id])
#name[:votes] += 1
respond_to do |format|
if #name.update_attributes(params[:name])
flash[:notice] = 'Candidate was upvoted'
format.html = { redirect_to :action => "index" }
format.xml = { head :ok }
else
format.html = { render :action => "index" }
format.xml = { render :xml => #name.errors, :status => :unprocessable_entity }
end
end
end
I do have the link in the view calling the correct action, it's trying to call :show, though.
please don't judge me too harshly lol...
The update_attributes method is generally used to set the fields of an ActiveRecord object from a form POST. The fields would be found as the hash params[:name], e.g. params[:name][:votes].
If you are clicking on a link to call the upvote method, then you are just doing a GET request. All you need to do is call #name.save to save the record.
def upvote
#name = Name.find(params[:id])
#name[:votes] += 1
respond_to do |format|
if #name.save
flash[:notice] = 'Candidate was upvoted'
format.html = { redirect_to :action => "index" }
format.xml = { head :ok }
else
format.html = { render :action => "index" }
format.xml = { render :xml => #name.errors, :status => :unprocessable_entity }
end
end
end
EDIT: From the comments, we also determined that the routes were set up improperly and that the link_to code in the view needed to include #name.id.
Typically the RESTful URL that maps to show is:
my_resource/id
So, e.g.,
candidates/1
Just at a guess, I'll bet if you look in config/routes.rb, you'll find something like:
map.resources :candidates
Where my_resource is the name of your controller. If you are going to use this kind of routing, then how does the resource provide upvoting? The custom method seems wise in this case, so:
map.resources :candidates, :collection => { :upvote => :post }
If you run
rake routes | grep candidate
before and after, you can see what's been added. Hope this helps.