Я создаю приложение для цитирования, в котором есть клиенты, сайты и кавычки.
У меня есть модель сайта, принадлежащая клиенту. Вы можете увидеть модель ниже.
Я хочу создать сайт и заполнить форму, как показано ниже.
Почему-то после установки простой формы ничего не сохраняется, не могу создать новый сайт.
Контроллер сайтов
class SitesController < ApplicationController
before_action :authenticate_user!
before_action :set_site, only: [:show, :edit, :update, :destroy]
# GET /sites
# GET /sites.json
def index
@sites = Site.all
end
# GET /sites/1
# GET /sites/1.json
def show
end
# GET /sites/new
def new
@site = Site.new
end
# GET /sites/1/edit
def edit
end
# POST /sites
# POST /sites.json
def create
@site = Site.new(site_params)
respond_to do |format|
if @site.save!
format.html { redirect_to @site, notice: 'Site was successfully created.' }
format.json { render :show, status: :created, location: @site }
else
format.html { render :new }
format.json { render json: @site.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /sites/1
# PATCH/PUT /sites/1.json
def update
respond_to do |format|
if @site.update(site_params)
format.html { redirect_to @site, notice: 'Site was successfully updated.' }
format.json { render :show, status: :ok, location: @site }
else
format.html { render :edit }
format.json { render json: @site.errors, status: :unprocessable_entity }
end
end
end
# DELETE /sites/1
# DELETE /sites/1.json
def destroy
@site.destroy
respond_to do |format|
format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_site
@site = Site.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def site_params
params.require(:site).permit(:name, :client_id)
end
end
Модель сайта
class Site < ApplicationRecord
belongs_to :client
has_many :quotes
end
Новая форма сайта
<div class="row">
<form class="col s12">
<div class="row">
<%= simple_form_for @site do |form| %>
<% if site.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(site.errors.count, "error") %> prohibited this site from being saved:</h2>
<ul>
<% site.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.input :name %>
<%= form.association :client %>
</div>
<div class="row">
<%= form.button :submit %>
</div>
<% end %>
</form>
</div>
Модель клиента
class Client < ApplicationRecord
has_many :sites
has_many :quotes
end
Клиентский контроллер
class ClientsController < ApplicationController
before_action :authenticate_user!
before_action :set_client, only: [:show, :edit, :update, :destroy]
# GET /clients
# GET /clients.json
def index
@clients = Client.all
end
# GET /clients/1
# GET /clients/1.json
def show
end
# GET /clients/new
def new
@client = Client.new
end
# GET /clients/1/edit
def edit
end
# POST /clients
# POST /clients.json
def create
@client = Client.new(client_params)
respond_to do |format|
if @client.save
format.html { redirect_to @client, notice: 'Client was successfully created.' }
format.json { render :show, status: :created, location: @client }
else
format.html { render :new, notice: 'Client was failed to create.' }
format.json { render json: @client.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /clients/1
# PATCH/PUT /clients/1.json
def update
respond_to do |format|
if @client.update(client_params)
format.html { redirect_to @client, notice: 'Client was successfully updated.' }
format.json { render :show, status: :ok, location: @client }
else
format.html { render :edit }
format.json { render json: @client.errors, status: :unprocessable_entity }
end
end
end
# DELETE /clients/1
# DELETE /clients/1.json
def destroy
@client.destroy
respond_to do |format|
format.html { redirect_to clients_url, notice: 'Client was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_client
@client = Client.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def client_params
params.require(:client).permit(:name, :site_id)
end
end
Я не получаю никаких ошибок, я просто не могу создать новый объект.
Started GET "/sites/new" for 127.0.0.1 at 2018-04-08 08:58:50 +1000
Processing by SitesController#new as HTML
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", "11121895-c5d0-42cc-b92c-4faf088d3f56"], ["LIMIT", 1]]
Rendering sites/new.html.erb within layouts/application
Client Load (0.3ms) SELECT "clients".* FROM "clients"
Rendered sites/_form.html.erb (56.1ms)
Rendered sites/new.html.erb within layouts/application (60.0ms)
Rendered shared/_header.html.erb (5.0ms)
Rendered shared/_footer.html.erb (0.7ms)
Completed 200 OK in 161ms (Views: 153.0ms | ActiveRecord: 0.8ms)
Started GET "/sites/new?utf8=%E2%9C%93&authenticity_token=YCl94xAEq8Ph%2F9Y5dbBOKoKeZnWVvJdw9khi%2Fotjnta4Qt%2BkJ9kYUlze%2FtaOyIzFG7YvT2MfJEr%2FYWNzrZ5VPw%3D%3D&site%5Bname%5D=hgh&site%5Bclient_id%5D=8276d1d3-9a79-4c27-94f0-346c044c2592&commit=Create+Site" for 127.0.0.1 at 2018-04-08 08:58:58 +1000
Processing by SitesController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"YCl94xAEq8Ph/9Y5dbBOKoKeZnWVvJdw9khi/otjnta4Qt+kJ9kYUlze/taOyIzFG7YvT2MfJEr/YWNzrZ5VPw==", "site"=>{"name"=>"hgh", "client_id"=>"8276d1d3-9a7-4c27-94f0-346c044c2592"}, "commit"=>"Create Site"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", "11121895-c5d0-42cc-b92c-4faf088d3f56"], ["LIMIT", 1]]
Rendering sites/new.html.erb within layouts/application
Client Load (0.4ms) SELECT "clients".* FROM "clients"
Rendered sites/_form.html.erb (11.8ms)
Rendered sites/new.html.erb within layouts/application (15.1ms)
Rendered shared/_header.html.erb (2.4ms)
Rendered shared/_footer.html.erb (0.6ms)
Completed 200 OK in 149ms (Views: 142.4ms | ActiveRecord: 1.2ms)
маршруты
Prefix Verb URI Pattern Controller#Action
sites GET /sites(.:format) sites#index
POST /sites(.:format) sites#create
new_site GET /sites/new(.:format) sites#new
edit_site GET /sites/:id/edit(.:format) sites#edit
site GET /sites/:id(.:format) sites#show
PATCH /sites/:id(.:format) sites#update
PUT /sites/:id(.:format) sites#update
DELETE /sites/:id(.:format) sites#destroy
pages_dashboard GET /pages/dashboard(.:format) pages#dashboard
import_quotes POST /quotes/import(.:format) quotes#import
quotes GET /quotes(.:format) quotes#index
POST /quotes(.:format) quotes#create
new_quote GET /quotes/new(.:format) quotes#new
edit_quote GET /quotes/:id/edit(.:format) quotes#edit
quote GET /quotes/:id(.:format) quotes#show
PATCH /quotes/:id(.:format) quotes#update
PUT /quotes/:id(.:format) quotes#update
DELETE /quotes/:id(.:format) quotes#destroy
clients GET /clients(.:format) clients#index
POST /clients(.:format) clients#create
new_client GET /clients/new(.:format) clients#new
edit_client GET /clients/:id/edit(.:format) clients#edit
client GET /clients/:id(.:format) clients#show
PATCH /clients/:id(.:format) clients#update
PUT /clients/:id(.:format) clients#update
DELETE /clients/:id(.:format) clients#destroy
users GET /users(.:format) users#index
user GET /users/:id(.:format) users#show
new_user_session GET /login(.:format) devise/sessions#new
user_session POST /login(.:format) devise/sessions#create
destroy_user_session DELETE /logout(.:format) devise/sessions#destroy
new_user_password GET /password/new(.:format) devise/passwords#new
edit_user_password GET /password/edit(.:format) devise/passwords#edit
user_password PATCH /password(.:format) devise/passwords#update
PUT /password(.:format) devise/passwords#update
POST /password(.:format) devise/passwords#create
cancel_user_registration GET /cancel(.:format) devise/registrations#cancel
new_user_registration GET /sign_up(.:format) devise/registrations#new
edit_user_registration GET /profile(.:format) devise/registrations#edit
user_registration PATCH / devise/registrations#update
PUT / devise/registrations#update
DELETE / devise/registrations#destroy
POST / devise/registrations#create
root GET / pages#dashboard
Только что попробовал ваши изменения... Не сохранил. Все еще нет ошибки. На самом деле я не думаю, что это правильно, так как до простой формы я мог создать сайт
@JeremyBray Где нет ошибки? Я думаю, вы можете увидеть
ROLLBACK
в консоли рельсов. Вы не можете создать объект own_to без ассоциации. Просто попробуйте сделать это вrails c
Ассоциация производится в форме? Отката нет обновлю чтобы показать
добавил лог для вас
@JeremyBray Верно. Мой плохой, не видел.
Товарищ, ваша помощь приветствуется.
какое имя пути вы ссылаетесь на your_path_name? У меня есть рейк-маршруты для вас
@JeremyBray Это
sites_path
.все та же проблема. Я думаю, что мы попали в кроличью нору, у меня такая же проблема со всеми моделями, даже с клиентом. Я не могу не чувствовать, что это что-то не так с простой установкой формы
Давайте продолжим это обсуждение в чате.