请记住,我在构建这个 Rails 应用程序时正在学习。
我的应用程序中有 2 个模型,部署和服务。服务有很多部署,每个部署都属于一个服务。在部署模型中,我有属性:service_name 和 :service_id,其中 :service_id 是外键。
我想让创建新部署的表单有一个字段:service_name,但没有:service_id,因为这样更直观。
这就是我试图在我的部署控制器中完成它的方式。
def create
@name = params[:deployment][:service_name]
@service = Service.find_by_name(@name)
**if @service.nil?
render :action => "new" , notice:'Service name (case sensitive) not found!'**
else
@deployment = @service.deployments.new(params[:deployment])
respond_to do |format|
if @deployment.save
format.html { redirect_to @service, notice: 'Deployment was successfully created.' }
format.json { render json: @service, status: :created, location: @service}
else
format.html { redirect_to @service, notice: 'Please enter all necessary fields.' }
format.json { render json: @deployment.errors, status: :unprocessable_entity }
end
只要用户为 :service_name 提交的任何内容都存在于我的服务表中,这一切都很好。否则,我会收到以下错误,因为 @service 将为空。
那么 Rails 专家,处理这个错误的最佳方法是什么?现在我有那个基本的 if 语句(粗体),但它并没有达到我的预期。谢谢!
NoMethodError in Deployments#create
Showing C:/ruby_training/ServiceRegistry/app/views/deployments/_form.html.erb where line #1 raised:
undefined method `model_name' for NilClass:Class
Extracted source (around line #1):
1: <%= form_for(@deployment) do |f| %>
2: <% if @deployment.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(@deployment.errors.count, "error") %> prohibited this deployment from being saved:</h2>
Trace of template inclusion: app/views/deployments/new.html.erb
Rails.root: C:/ruby_training/ServiceRegistry
Application Trace | Framework Trace | Full Trace
app/views/deployments/_form.html.erb:1:in `_app_views_deployments__form_html_erb___545233454_35802348'
app/views/deployments/new.html.erb:3:in `_app_views_deployments_new_html_erb__57703416_31561704'
app/controllers/deployments_controller.rb:56:in `create
'