在我的控制器中,我创建了两个单独的new
操作。一个是asknew
,另一个是offernew
。我需要在创建每个值时设置它们的值,因此我尝试为每个值创建一个单独的create
操作,我可以在其中设置两个不同的值。
def newoffer
@request = Request.new
@request.requesttype = "offer"
end
def newask
@request = Request.new
@request.requesttype = "ask"
end
自定义创建操作:
def createask
@request = Request.new(request_params)
@request.requesttype = "ask"
respond_to do |format|
if @request.save
format.html { redirect_to @request, notice: 'Request was successfully created.' }
format.json { render :show, status: :created, location: @request }
else
format.html { render :new }
format.json { render json: @request.errors, status: :unprocessable_entity }
end
end
end
def createoffer
@request = Request.new(request_params)
@request.requesttype = "offer"
respond_to do |format|
if @request.save
format.html { redirect_to @request, notice: 'Request was successfully created.' }
format.json { render :show, status: :created, location: @request }
else
format.html { render :new }
format.json { render json: @request.errors, status: :unprocessable_entity }
end
end
end
所有操作都运行正常,但我不知道如何让new
操作路由到各自的create
操作。顺便说一句,路由有哪些好资源?这是我遇到的最麻烦的事情。
答案 0 :(得分:1)
要避免单独的new和create操作来设置requesttype默认值,您可以通过url传递值并将其存储在隐藏的表单字段中:
<强>链接:强>
link_to('New offer', new_request_path(requesttype: 'offer'))
link_to('New ask', new_request_path(requesttype: 'ask'))
<强>控制器:强>
def new
@request = Request.new(requesttype: params[:requesttype])
end
<强>表格强>
form_for(@request) do |f|
f.hidden_field :requesttype
end
确保您在模型图层中验证requesttype,以防有人混淆URL
class Request < ActiveRecord::Base
validates_inclusion_of :requesttype, in: %w{ offer ask }
end