简体   繁体   English

Rails - 将客户端 model 保存到数据库中

[英]Rails - Save client model into the database

Hey here.嘿这里。 I'm kinda new to Rails and I've been trying to find some answers but no luck yet so here we go.我对 Rails 有点陌生,我一直在试图找到一些答案,但还没有运气,所以我们开始吧。

I've set up a basic Rails app and just trying to save a Client to my database with a validation but nothing seems to be coming together.我已经设置了一个基本的 Rails 应用程序,只是试图通过验证将客户端保存到我的数据库中,但似乎没有任何东西可以组合在一起。 Anyone could point me to the right direction please or let me know what I've been doing wrong in my code.任何人都可以向我指出正确的方向,或者让我知道我在代码中做错了什么。

I keep getting errors like this:我不断收到这样的错误:

NoMethodError in Clients#new
Showing /Users/******/Documents/******/*****/app/views/clients/_form.html.erb where line #1 raised:

undefined method `clients_path' for #<ActionView::Base:0x00000000064a50>
Did you mean?  clients_new_path

Even if I remove @client = Client.new from the new method I can view the page but nothing gets saved.即使我new方法中删除@client = Client.new ,我也可以查看该页面,但没有保存任何内容。

I'm stuck really now so any help much appreciated!我现在真的被困住了,所以非常感谢任何帮助! Thanks!谢谢!

My Routes.rb file:我的Routes.rb文件:

Rails.application.routes.draw do
  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
  get 'dashboard/index'
  root to: "home#index"

  devise_for :users, controllers: {
    sessions: 'users/sessions',
    passwords: 'users/passwords',
    registrations: 'users/registrations'
  }

  get '/clients/index'
  get '/clients/new'
  get '/clients/edit'
  get '/clients/delete'

  get '/clients/:id', to: 'clients#show'

  post '/clients/new', to: 'clients#create'
end

My Dashboard file:我的仪表板文件:

<% if user_signed_in? %>
    <nav class="subnav">
        <ul>
            <li><%= link_to('My Clients', clients_index_path) %></li>
            <li><%= link_to('Add Client', clients_new_path) %></li>
            <li><%= link_to('Edit registration', edit_user_registration_path) %></li>
            <li><%= link_to('Logout', destroy_user_session_path, :method => :delete) %></li>
        </ul>
    </nav>
<% else %>

  <%= link_to('Register', new_user_registration_path)  %>
  <%= link_to('Login', new_user_session_path)  %>

<% end %>

My ClientsController file:我的ClientsController文件:

class ClientsController < ApplicationController
  def index
    @clients = Client.all
  end

  def new
    @client = Client.new
  end

  def show
    @client = Client.find(params[:id])
  end

  def create
    @client = Client.new(client_params)

    if @client.save
      redirect_to @client
    else
      render :new
    end
  end

  def edit
  end

  def delete
  end

  private
    def client_params
      params.require(:client).permit(:name, :provider)
    end
end

My form :我的表格

<%= form_with model: @client do |form| %>
  <div>
    <%= form.label :name %><br>
    <%= form.text_field :name %>
    <% client.errors.full_messages_for(:name).each do |message| %>
      <div><%= message %></div>
    <% end %>
  </div>

  <div>
    <%= form.label :provider %><br>
    <%= form.text_field :provider %>
  </div>

  <div>
    <%= form.label :business_type %><br>
    <%= form.select :business_type, ["Partnership", "Sole Trader", "Limited Company"] %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

Finally my new.html.erb file:最后是我的new.html.erb文件:

<h1>Clients#new</h1>

<%= render 'form', client: @client %>

clients_path is generated by resources:clients, only: :index or you probably need to give your route the name you want. clients_pathresources:clients, only: :index生成,或者您可能需要为您的路线指定您想要的名称。 Try this尝试这个

get '/clients/index', as: :clients

or, if you want to specify non default paths as you're doing, your index is probably called clients_index_path , but you can check that with a rake routes or rails routes , because I'm not sure.或者,如果您想指定非默认路径,您的索引可能称为clients_index_path ,但您可以使用rake routesrails routes检查,因为我不确定。

That said, I suggest you to go with the resources method in your routes file and use the default paths as you're trying to do.也就是说,我建议您使用路由文件中的resources方法 go 并使用默认路径,就像您尝试做的那样。 Something like就像是

resources :clients

but now you don't have a path like /clients/index no more, just /clients for the index action.但是现在您不再有像/clients/index这样的路径,只有/clients用于索引操作。

If you're in doubts with routes try to read the guide about routing如果您对路线有疑问,请尝试阅读有关路线的指南

The Rails way to declare the routes to Create, Update, Read and Destroy (CRUD) a resource is just: Rails 声明创建、更新、读取和销毁 (CRUD) 资源的路由的方式是:

Rails.application.routes.draw do
  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
  get 'dashboard/index'
  root to: "home#index"

  devise_for :users, controllers: {
    sessions: 'users/sessions',
    passwords: 'users/passwords',
    registrations: 'users/registrations'
  }

  resources :clients
end

As you can see by the annotions above each method Rails does not add the "action" to the path except for the new and edit routes:正如您从每个方法上面的注释中看到的那样,Rails 不会将“动作”添加到路径中,除了new的和edit的路线:

class ClientsController < ApplicationController
  before_action :set_client, only: [:show, :edit, :update, :destroy]

  # GET /clients
  def index
    @clients = Client.all
  end

  # GET /clients/1
  def show
  end
  
  # GET /clients/new
  def new
    @client = Client.new
  end

  # POST /clients
  def create
    @client = Client.new(client_params)

    if @client.save
      redirect_to @client
    else
      render :new
    end
  end

  # GET /clients/edit
  def edit
  end

  # PATCH /clients/1
  def update
    if @client.update(client_params)
      redirect_to @client
    else
      render :edit
    end
  end

  # DELETE /clients/1
  def delete
    @client.destroy
    redirect_to action: :index, 
                notice: 'Client deleted'
  end

  private
    def set_client
      @client = Client.find(params[:id])
    end

    def client_params
      params.require(:client).permit(:name, :provider)
    end
end

Thus you don't create resources with post '/clients/new' - You use POST /clients .因此,您不会使用post '/clients/new'创建资源 - 您使用POST /clients Also when you use the "bare-bones" routing methods such as match , get , post etc Rails does not automatically add routing helper.此外,当您使用诸如matchgetpost等“基本”路由方法时,Rails 不会自动添加路由助手。 If you actually wanted to generate the equivilent routes you would need to use:如果你真的想生成你需要使用的等价路线:

post '/clients', 
  to: 'clients#create',
  as: :clients

But you're much better off embracing the conventions and learning to use them to be productive.但是你最好接受约定并学习使用它们来提高工作效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM