属于项目时无法创建新界面

时间:2019-04-27 10:19:07

标签: ruby-on-rails

我尝试创建一个新的接口对象。单击创建按钮后,它仍然保留new.html.erb,应该转到project_interfaces_path(主页)。另外,数据尚未保存。

我尝试了许多方法,例如更改URL,但是它不起作用,并且在InterfacesController#create中报告NoMethodError nil:NilClass的未定义方法“接口”

interface/new.html.erb

<div class="card-body">
    <%= form_for @interface, url:project_interfaces_path,method: :post do |f| %>
      <div class="form-group">
        <%= f.label :name %>
        <%= f.text_area :name,class: 'form-control'%>
      </div>
      <div class="form-group">
        <%= f.label :desp %>
        <%= f.text_field :desp,class:'form-control'%>
      </div>
      <div class="form-group">
        <%= f.label :request_url %>
        <%= f.text_field :request_url,class:'form-control'%>
      </div>
      <div class="form-group">
        <%= f.label :request_eg %>
        <%= f.text_field :request_eg,class:'form-control'%>
      </div>
      <div class="form-group">
        <%= f.label :response_eg %>
        <%= f.text_field :response_eg,class:'form-control'%>
      </div>
      <%=link_to  project_interfaces_path  do%>
        <button type="button" class="btn btn-primary">返回列表</button>
      <% end %>
      <%=f.submit "创建",class: 'btn btn-primary' %>
    <% end %>

接口控制器:

  def new
    @interface = Interface.new
  end

  def create
    @interface = @project.interfaces.new(interface_params)
    if @interface.save
      redirect_to project_interfaces_path
    else
      render :new 
    end
  end

private
  def interface_params
    params.require(:interface).permit(:id, :name, :desp,:request_url,:request_eg,:response_eg)
  end

该接口属于项目:

class Interface < ApplicationRecord
  belongs_to :method_type
  has_many :get_fields, dependent: :destroy
  has_many :put_fields, dependent: :destroy
  belongs_to :project
end

2 个答案:

答案 0 :(得分:0)

实际上,您是重定向到new而不是project_interfaces_path

def create
  @interface = Interface.new(interface_params)
  if @interface.save
    #redirect_to new_project_interface_path(project) <- wrong path
    redirect_to project_interfaces_path # Good path
  else
    render :new 
  end
end

还要在url:的{​​{1}}和project_interfaces_path之间添加一个空格。

更新:看来您正在尝试保存<%= form_for @interface, url:project_interfaces_path,method: :post do |f| %>,而没有将Interface与之关联。

您需要检索一个项目并使用它来构建界面

Project

看看您的路线会有所帮助。

答案 1 :(得分:0)

您正在使用嵌套资源,这意味着自接口belongs_to :project起,如果没有project_id,就无法创建接口。应该如何:

def new
  @project = Project.find(params[:project_id])
  @interface = @project.interfaces.new
end

def create
  @project = Project.find(params[:project_id])
  @interface = @project.interfaces.build(interface_params)
  if @interface.save
    redirect_to project_interfaces_path(@project)
  else
    render :new 
  end
end

private
def interface_params
  params.require(:interface).permit(:id, :name, :desp,:request_url,:request_eg,:response_eg)
end

并从表单中删除url和方法选项,它会自动运行

<%= form_for @interface do |f| %>