【发布时间】:2016-03-25 13:06:24
【问题描述】:
我有一个控制器,farms_controller,用于两条不同的路线,farms 和 person_farms;这两条路线使用相同的文件夹作为视图模板(即new_person_farm_path 和new_farm_path 使用相同的模板new.html.erb)。我想分别访问农场注册页面和个人注册内部,其中某些功能是不同的,在某些测试中使用 URL 来显示不同的功能(通过request.env['PATH_INFO'].include? 'person_farms',因为我不知道最好的方法)。
当我在没有来自new_person_farm_path 的必填字段(名称)的情况下提交时,create 函数会为不正确的字段呈现具有不同样式的new_farm_path 页面(使用'twitter-bootstrap-rails' gem)。我希望它使用相同的模板文件但不同的路由(不同的 URL)来呈现 new_person_farm_path 页面。我尝试使用redirect_to,它在正确的 URL 中显示页面,但在错误的字段中没有样式。
但是,我在Rails documentation for rendering 中看到的所有指令都在渲染特定文件,但这不是我需要的。我有一种感觉,这不是“Rails 方式”,但我是 RoR 的初学者,这是一个正在重写为 Rails 的遗留系统,所以我现在无法更正数据库逻辑。
那么,有没有办法从同一个控制器渲染一个视图,但使用不同的路由?
我的代码:
def create
@farm = Farm.new(farm_params)
respond_to do |format|
if @farm.save
# Param sent by the page to test if I'm in a person_farms page
# instead of a farms page because the request.env test doesn't work here.
# I feel that this is not the correct way to do that, but I can leave the correct way to another question.
# However, if someone has a suggestion a comment would be appreciated.
if params[:is_person_farm_page]
format.html { redirect_to @person_farm_path(@farm), notice: 'Farm saved' }
format.json { render :show, status: :created, location: @farm }
else
format.html { redirect_to @farm, notice: 'Farm saved' }
format.json { render :show, status: :created, location: @farm }
end
else
#This is the point where I want to redirect to new_person_farm_path
#I would need to test using the params[:is_person_farm_page] above
format.html { render :new }
format.json { render json: @farm.errors, status: :unprocessable_entity }
end
end
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4