开发者

rails, rest, render different action with responds to

开发者 https://www.devze.com 2022-12-27 00:07 出处:网络
Maybe my logic is not restful or know if this is how you would do it but this is what I am trying to do.

Maybe my logic is not restful or know if this is how you would do it but this is what I am trying to do.

I'm getting a category inside a category controller and then once I get that category I want to return to an index page in a different controller but keep that @category and the Category.busineses.

Before rest I would have just done this:

render :controller => "businesses"

and it would have rendered the view of the index action in that controller.

now in my respond_to block I have this

   format.html {redirect_to(business_path)} # index.html.erb
   format.xml  { render :xml => @businesses }

but of course with a render it looses the instance variable and starts with a new action.

So what I want to do is render the action instead of 开发者_如何学编程redirecting to that action. is this possible?

Should i just replace the respond_to with render :controller => ?


I think what you are trying to do (if I understand it correctly) would be best achieved using nested resources. If there are businesses separated into categories, and you want to display a listing of all businesses in a specific category, you could set up your application like this:

Models

class Category < ActiveRecord::Base
  has_many :businesses
end

class Business < ActiveRecord::Base
  belongs_to :category
end

Routes

map.resouces :businesses

map.resources :categories do |categories|
  categories.resources :businesses
end

Controller

class BusinessesController < ApplicationController
  def index
    @category = Category.find(params[:category_id]) if params[:category_id]
    conds = params[:category_id] ? { :category_id => params[:category_id] } : nil
    @businesses = Business.all(:conditions => conds)
  end
end

Then simply access the list of a category's businesses like this: /category/1/businesses


I am not 100% clear of what you are trying to do, but you have several options for presentation in a RESTful app.

You can pass a parameters in a redirect. In this case we pass the category id as a parameter in the HTTP GET. The page on the end of the redirect can then handle this appropriately:

format.html {redirect_to( business_path(:category_id => @category.id) }

You can also render the view of a specified action or template. In this case we render the view defined in "{current_controller}/business.html.erb":

format.html { render :action => "business" }


You cann't use redirect_to if you want instance variable as it is use render as follows.

format.html { render :controller=> 'buisness'  ,:action => "index" }

OR JUSt

format.html { render :controller=> 'buisness'}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号