Я создаю небольшое приложение Rails с аутентификацией пользователя. Это приложение, в котором вы можете организовывать свои проекты, добавлять в него задания, добавлять комментарии.redirect_to action в Create issue Ruby on Rails
Когда я являюсь текущим пользователем, я могу нажать «начать проект» и увидеть форму. Но когда я отправляю форму, она перенаправляет меня на индекс проектов (это то, что я хочу), но он не сохраняет проект; Вместо этого у меня есть сообщение об ошибке. Во всяком случае, вы можете увидеть его с кодом:
Вот мой project.rb
:
class Project < ActiveRecord::Base
belongs_to :user
validates_presence_of :name, :deadline, :description
attr_accessor :name, :deadline, :description
end
Вот мой projects_controller.rb
:
class ProjectsController < ApplicationController
include ActiveModel::Model
attr_accessor :name, :deadline, :description
validates :name, presence: true
validates :deadline, presence: true
validates :description, presence: true
def index
@projects = Project.all
end
def new
@project = Project.new
end
def create
@project = Project.new(project_params)
if @project.save
redirect_to projects_show_path, notice: 'Project successfully added'
else
flash[:alert] = 'An error ocurred adding your project. Please try again later'
redirect_to projects_index_path
end
end
def show
@current_user = User.find(params[:id])
@project = Project.find(params[:id])
end
def edit
@project = Project.find(params[:id])
end
def update
@project = Project.find(params[:id])
if @project.update_attributes(project_params)
redirect_to projects_index_path
else
flash[:alert] = "An occurred editing your project. Please try again later"
redirect_to projects_index_path
end
end
def destroy
@project = Project.find(params[:id])
if @project.destroy
redirect_to projects_index_path
else
flash[:alert] = "An error occured deleting your project... Please try again later"
redirect_to projects_index_path
end
end
private
def project_params
params.require(:project).permit(:name, :deadline)
end
end
Вот мой projects/index.html.erb
:
<body id="projects-index-body">
<div id="welcome-projects">
<h1>Hi <% @current_user %> ! Start managing your projects !</h1>
</div>
<div id="projects-index-container>">
<% if @project.nil? %>
<div id="no-project">
<p>You don't have any projects <%= link_to 'yet', projects_new_path %>.</p>
</div>
<% else %>
<%= render @projects %>
<% end %>
</div>
</body>
Вот мой _form.html.erb
:
<div id="form-new-project-container">
<%= form_for @project do |f| %>
<div id="form-input">
<%= f.text_field :name, placeholder: 'Project name', autofocus: true %>
</div>
<div id="form-input">
<%= f.text_field :deadline, placeholder: 'What is your project deadline ?', autofocus: true %>
</div>
<div id="form-input">
<%= f.text_area :description, placeholder: 'Add a description', autofocus: true, style: 'height:100px' %>
</div>
<div id="form-submit">
<%= f.submit('Add project', class: 'submit-btn') %>
</div>
<% end %>
</div>
Вот мой _projects.html.erb
:
<div id="name-container">
<%= link_to "#{@projects.name}", project %>
</div>
Вот мои routes.rb
:
Rails.application.routes.draw do
get 'projects/index'
get 'projects/show'
get 'projects/edit'
get 'projects/new'
get 'welcome/index'
get 'welcome/about'
resources :projects
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
resources :users do
delete 'users/sign_out' => "devise/sessions#destroy"
end
authenticated :users do
root to: 'projects#index', as: :authenticated_root
end
root 'welcome#index'
end
Бревна в development.log
:
Started GET "/projects/new" for ::1 at 2016-10-12 16:40:01 +1100
Processing by ProjectsController#new as HTML
Rendered projects/_form.html.erb (17.2ms)
Rendered projects/new.html.erb within layouts/application (20.7ms)
[1m[36mUser Load (0.1ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1[0m [["id", 3]]
Completed 200 OK in 74ms (Views: 72.7ms | ActiveRecord: 0.1ms)
Started GET "/projects/new" for ::1 at 2016-10-12 17:10:20 +1100
Processing by ProjectsController#new as HTML
Rendered projects/_form.html.erb (1.7ms)
Rendered projects/new.html.erb within layouts/application (2.7ms)
[1m[35mUser Load (0.2ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 3]]
Completed 200 OK in 62ms (Views: 51.2ms | ActiveRecord: 1.0ms)
Started GET "/assets/application.self-64b323fda93125b3149a63eb79976d7aca18fdd68d693ad1ef615b0ab4a62cd2.css?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/jquery_ujs.self-784a997f6726036b1993eb2217c9cb558e1cbb801c6da88105588c56f13b466a.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/menu.self-5ad0c1c387d3f54736adf9854f4fd424128328e7958f16a7e3f9c96cd1a85c41.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/angular/angular.self-7f8df3e3ebe7623e233b951726e7da238883fa9e7a98b987ac7aecccf5f00510.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/projects.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/users.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/users/omniauth_callbacks.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/welcome.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started GET "/assets/application.self-f8806224e027f3e3f0138ea9ce99319e298dfdb323304d1f1be6eae8e8c74724.js?body=1" for ::1 at 2016-10-12 17:10:20 +1100
Started POST "/projects" for ::1 at 2016-10-12 17:10:22 +1100
Processing by ProjectsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"RVkKamdrg/DM2rmDxclNqt0hurD29Fvg1TECS46y/PCAXJ4mn2cyus16IvOikPLpO+cyto99X2jH6vX8JZO/pQ==", "project"=>{"name"=>"", "deadline"=>"", "description"=>""}, "commit"=>"Add project"}
Unpermitted parameter: description
[1m[36m (0.1ms)[0m [1mbegin transaction[0m
[1m[35m (0.0ms)[0m rollback transaction
Redirected to http://localhost:3000/projects/index
Completed 302 Found in 4ms (ActiveRecord: 0.1ms)
Started GET "/projects/index" for ::1 at 2016-10-12 17:10:22 +1100
Processing by ProjectsController#index as HTML
Rendered projects/index.html.erb within layouts/application (0.1ms)
[1m[36mUser Load (0.1ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1[0m [["id", 3]]
Completed 200 OK in 23ms (Views: 22.8ms | ActiveRecord: 0.1ms)
Started GET "/projects/index" for ::1 at 2016-10-12 17:11:29 +1100
Processing by ProjectsController#index as HTML
Rendered projects/index.html.erb within layouts/application (0.2ms)
[1m[35mUser Load (0.1ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 3]]
Completed 200 OK in 39ms (Views: 35.3ms | ActiveRecord: 0.6ms)
Started GET "/assets/jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1" for ::1 at 2016-10-12 17:11:29 +1100
Started GET "/assets/turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1" for ::1 at 2016-10-12 17:11:29 +1100
Started GET "/assets/jquery_ujs.self-784a997f6726036b1993eb2217c9cb558e1cbb801c6da88105588c56f13b466a.js?body=1" for ::1 at 2016-10-12 17:11:30 +1100
Started GET "/assets/angular/angular.self-7f8df3e3ebe7623e233b951726e7da238883fa9e7a98b987ac7aecccf5f00510.js?body=1" for ::1 at 2016-10-12 17:11:30 +1100
Started GET "/assets/menu.self-5ad0c1c387d3f54736adf9854f4fd424128328e7958f16a7e3f9c96cd1a85c41.js?body=1" for ::1 at 2016-10-12 17:11:30 +1100
Started GET "/assets/application.self-64b323fda93125b3149a63eb79976d7aca18fdd68d693ad1ef615b0ab4a62cd2.css?body=1" for ::1 at 2016-10-12 17:11:30 +1100
Started GET "/assets/projects.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" for ::1 at 2016-10-12 17:11:30 +1100
Started GET "/assets/users.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" for ::1 at 2016-10-12 17:11:30 +1100
Started GET "/assets/users/omniauth_callbacks.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" for ::1 at 2016-10-12 17:11:30 +1100
Started GET "/assets/welcome.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" for ::1 at 2016-10-12 17:11:30 +1100
Started GET "/assets/application.self-f8806224e027f3e3f0138ea9ce99319e298dfdb323304d1f1be6eae8e8c74724.js?body=1" for ::1 at 2016-10-12 17:11:30 +1100
Started GET "/projects/new" for ::1 at 2016-10-12 17:11:31 +1100
Processing by ProjectsController#new as HTML
Rendered projects/_form.html.erb (3.2ms)
Rendered projects/new.html.erb within layouts/application (14.4ms)
[1m[36mUser Load (0.1ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1[0m [["id", 3]]
Completed 200 OK in 57ms (Views: 51.8ms | ActiveRecord: 0.3ms)
Started POST "/projects" for ::1 at 2016-10-12 17:11:33 +1100
Processing by ProjectsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"s9h2ktiveACV3Mq4JJsz1/Z3eE5R+wlejmikisQI1BJ23eLeIKPJSpR8UchDwoyUELHwSChyDdacs1M9bymXRw==", "project"=>{"name"=>"", "deadline"=>"", "description"=>""}, "commit"=>"Add project"}
Unpermitted parameter: description
[1m[35m (0.1ms)[0m begin transaction
[1m[36m (0.1ms)[0m [1mrollback transaction[0m
Redirected to http://localhost:3000/projects/index
Completed 302 Found in 5ms (ActiveRecord: 0.2ms)
Started GET "/projects/index" for ::1 at 2016-10-12 17:11:33 +1100
Processing by ProjectsController#index as HTML
Rendered projects/index.html.erb within layouts/application (0.2ms)
[1m[35mUser Load (0.1ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 3]]
Completed 200 OK in 23ms (Views: 21.6ms | ActiveRecord: 0.1ms)
Я уже сделал PROJEC t нравится это раньше, и этот вопрос никогда не возникал. Вот почему я не понимаю. Я, конечно, что-то пропустил.
Надеюсь, вы поймете это :) Я все еще работаю над этим ...
Какая ошибка вы получаете ..! –
Да, что сообщение об ошибке? и вы упомянули, что «Но когда я отправляю форму, она перенаправляет меня на индекс проектов (который я хочу)».Но согласно твоему действию, он будет перенаправлен на «индекс», если есть ошибка, иначе перенаправляется на страницу «показать», поэтому, если вы хотите перенаправить на «индекс», то тоже измените это значение – Sajan
Ошибка внутри контроллера внутри действия create , 'flash [: alert] = 'Произошла ошибка с добавлением вашего проекта. Повторите попытку позже. Потому что, когда я нажимаю на добавление проекта для отправки формы, он перенаправляет меня на индекс. Но вместо проекта появляется сообщение об ошибке. – justinedps26