Rails redirect_to 时怎么解构 params 传参数

newRer · September 18, 2017 · Last by newRer replied at September 19, 2017 · 1646 hits

我在 edit 方法判断如果没有新的 model,就 new 一个,这时候原有的散列需要传进去,可是我觉得 code: params[:code], date: params[:date] 写法太难看,试了几种别的不行,应该可以解构这个散列,不知道怎么写

 def edit
  ...
  if st.count > 0
    @strategy = st.first
  else
    redirect_to controller: 'strategies', action: 'new', code: params[:code], date: params[:date]
  end
end

def new
    @strategy = Strategy.new(code: params[:code], date: params[:date])
end

def strategy_params
    params.require(:strategy).permit(:code, :date)
end

edit 方法为什么要负责 new 啊……

代码没写全,edit 会先查找另一个实体,如果不存在就 new 一个

redirect_to request.params.slice(:code, :date).merge({ action: :new })
  • request.params 会取当前参数,然后选择其中的 code, date
  • controller 键可以省略,默认取当前
Reply to pinewong

谢谢,要的就是这个

newRer closed this topic. 19 Sep 14:56
You need to Sign in before reply, if you don't have an account, please Sign up first.