【发布时间】:2017-01-17 02:53:40
【问题描述】:
我是新手。我的 rails 版本是 4.2.6,simple_form_for 版本是 3.2.1。在验证参数为假后,我想重定向到新页面。我收到错误消息。
nil:NilClass ...
让我告诉你。这是我的 routes.rb
namespace :account do
resources :stations, expect: [:index]
end
stations_controller.rb
def new
@lines = Line.where(line_status: 1)
@station = Station.new
end
def create
unless check_post_params post_params
flash[:notice] = "miss params"
render action: :new # not work
# render :new # not work
# render 'new' # not work
# it work for me, but can I use render?
#redirect_to '/account/stations/new'
else
@station = Station.new(post_params)
if @station.save
redirect_to '/account/lines'
else
flash[:notice] = 'failed'
redirect_to 'account/stations/new'
end
end
end
private
def post_params
params.require(:station).permit(...)
end
def check_post_params(post_params)
if ...
return false
else
return true
end
end
_form.html.erb
<%= simple_form_for [:account, @station] do |f| %>
<div class="form-group">
<%= f.label :line_id, t('line.line_name') %>
<%= f.input_field :line_id,
... %>
<% end %>
原来我打开的网址是http://localhost:3000/acoount/stations/new。单击提交后,我想render :new,它会重定向到原始URL,但我发现URL变成了http://localhost:3000/account/stations。 URL 的/new 消失了。我猜这与我的routes.rb 配置有关。
我尝试使用rake routes 来检查我的路线。
$ rake routes
...
POST /account/stations(.:format) account/stations#create {:expect=>:index]}
new_account_station GET /account/stations/new(.:format) account/stations#new {:expect=>[:index]}
...
我尝试使用render account_stations_new_path 和render new_account_station_path,但仍然不适合我。谢谢你的帮助。
编辑
我知道如何修改我的代码。我应该在我的模型上验证我的参数。然后我应该使用redirect_to 不使用渲染。我稍后会更新我的代码。
编辑 2
我修改了我的模型。
class Station < ActiveRecord::Base
belongs_to :line
has_many :spot_stations
validates :name, presence: true, uniqueness: { case_sensitive: false }
validates :line_id, presence: true
validates ....
end
我修改了我的控制器。
def new
# Because this @lines did't exist when I render 'new' on the create method. So I deleted it. And I create a method on the helper.
# @lines = Line.where(line_status: 1)
@station = Station.new
end
def create
@station = Station.new(post_params)
if @station.save
redirect_to '/account/lines'
else
flash[:notice] = 'failed'
render 'new'
end
end
我添加了一个获取行数据的方法
module Account::StationsHelper
def get_lines
@lines = Line.where(line_status: 1)
end
end
我将在我的 _form.html.erb
上使用它<%= simple_form_for [:account, @station] do |f| %>
<div class="form-group">
<%= f.label :line_id, t('line.line_name') %>
<%= f.input_field :line_id,
collection: get_lines,
label_method: :line_name,
input_html: { class: 'form-control' },
value_method: :id,
prompt: t('common.please_select') %>
</div>
...
<% end %>
这项工作对我来说很棒。谢谢你的帮助。
【问题讨论】:
标签: ruby-on-rails ruby