#ruby-on-rails #object
#ruby-on-rails #объект
Вопрос:
В моем коде у меня есть это :
def confirm
@pal = Pal.find(params[:palid])
@newuser = User.new(newuser_params)
@newuser.username = @pal.phone
if @newuser.save
redirect_to(:controller => 'access', :action => 'index')
else
flash[:error] = "Retry."
render template: 'pals/new_password_asign'
end
end
private
def newuser_params
params.require(:newuser).permit(:username, :password_digest, :password_stored)
end
и после отправки моей формы регистрации я получаю перенаправление и ошибку «Повторить попытку», которую я указал.
Зная, что я создаю пользователей и сохраняю их через rails console
, все в порядке.
И это заставило меня задуматься, что могло бы помешать этому сохранению? Какие проблемы могут возникнуть во время сохранения?
======================================================
Rails v4
Ruby v2.02
Я использую Bcrypt-ruby для аутентификации.
======================================================
Обновление # 1
=======================================================
После добавления предложенного решения @mandeep, я теперь получаю объяснение ошибки, и в этом объяснении я получаю
» Пароль не может быть пустым»
Несмотря на то, что я пишу пароль перед отправкой
Проверьте мою форму регистрации
<%= form_for(:newuser, :url => {:action => 'confirm', :palid => @pal.id}) do |f| %>
<% if @newuser.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@newuser.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @newuser.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<table summary="user form fields">
<tr>
<th><%= f.label(:username, "User Name") %></th>
<td><%= f.text_field :username, :value => @newuser.username, :class => "controls", :disabled => "true" %></td>
</tr>
<tr>
<th><%= f.label(:password, "password") %></th>
<td><%= f.password_field(:password) %></td>
</tr>
</table>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
</div>
<% end %>
<% @newuser.password_stored = @newuser.password %>
</div>
</body>
==============================================
Обновление # 2
Журнал и параметры после запроса @mandeep
Started GET "/pals" for 127.0.0.1 at 2014-07-03 16:15:44 0000
ActiveRecord::SchemaMigration Load (0.1ms) SELECT `schema_migrations`.* FROM `schema_migrations`
Processing by palsController#index as HTML
pal Load (0.4ms) SELECT `pals`.* FROM `pals`
Rendered pals/index.html.erb within layouts/application (9.8ms)
Completed 200 OK in 280ms (Views: 260.9ms | ActiveRecord: 0.4ms)
Started GET "/pals" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Processing by palsController#index as HTML
pal Load (0.7ms) SELECT `pals`.* FROM `pals`
Rendered pals/index.html.erb within layouts/application (6.3ms)
Completed 200 OK in 103ms (Views: 101.4ms | ActiveRecord: 0.7ms)
Started GET "/assets/access.css?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/bootstrap_and_overrides.css?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/pals.css?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/users.css?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-transition.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-alert.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-modal.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-dropdown.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-scrollspy.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-tab.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-tooltip.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-popover.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-button.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-collapse.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-carousel.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-typeahead.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap/bootstrap-affix.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/twitter/bootstrap.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/turbolinks.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:45 0000
Started GET "/assets/access.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:46 0000
Started GET "/assets/bootstrap.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:46 0000
Started GET "/assets/pals.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:46 0000
Started GET "/assets/users.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:46 0000
Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2014-07-03 16:15:46 0000
Started GET "/pals/new" for 127.0.0.1 at 2014-07-03 16:16:11 0000
Processing by PalsController#new as HTML
Rendered pals/_form.html.erb (24.7ms)
Rendered pals/new.html.erb within layouts/application (43.6ms)
Completed 200 OK in 106ms (Views: 101.2ms | ActiveRecord: 1.6ms)
Started POST "/pals" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Processing by PalsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8X6LD0g6E1HybdAF/FOlM09iuQLWExBY8dY5CqSDZsM=", "pal"=>{"owner"=>"John", "title"=>"", "phone"=>"22", "price"=>"", "logtype"=>"", "description"=>"", "address"=>"", "latitude"=>"", "longitude"=>""}, "commit"=>"Create pal"}
(0.3ms) BEGIN
SQL (0.3ms) INSERT INTO `pals` (`address`, `created_at`, `description`, `logtype`, `owner`, `phone`, `title`, `updated_at`) VALUES ('', '2014-07-03 16:16:19', '', '', 'John', '22', '', '2014-07-03 16:16:19')
(56.6ms) COMMIT
User Load (0.1ms) SELECT `users`.* FROM `users` WHERE `users`.`username` = '22'
Redirected to http://localhost:3000/pals/confirm?palid=5
Completed 302 Found in 77ms (ActiveRecord: 58.1ms)
Started GET "/pals/confirm?palid=5" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Processing by PalsController#confirm as HTML
Parameters: {"palid"=>"5"}
pal Load (0.6ms) SELECT `pals`.* FROM `pals` WHERE `pals`.`id` = 5 LIMIT 1
Rendered pals/confirm.html.erb within layouts/application (6.4ms)
Completed 200 OK in 63ms (Views: 52.4ms | ActiveRecord: 0.8ms)
Started GET "/assets/access.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/pals.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/bootstrap_and_overrides.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/users.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-transition.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-alert.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-modal.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-dropdown.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-tab.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-scrollspy.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-tooltip.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-popover.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-button.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-collapse.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-carousel.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-typeahead.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap/bootstrap-affix.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/twitter/bootstrap.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/access.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/turbolinks.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/bootstrap.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/pals.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/users.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:19 0000
Started POST "/pals/confirm?palid=5" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Processing by PalsController#confirm as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8X6LD0g6E1HybdAF/FOlM09iuQLWExBY8dY5CqSDZsM=", "newuser"=>{"password"=>"[FILTERED]"}, "commit"=>"Save Newuser", "palid"=>"5"}
pal Load (0.2ms) SELECT `pals`.* FROM `pals` WHERE `pals`.`id` = 5 LIMIT 1
(0.6ms) BEGIN
(0.1ms) COMMIT
(0.1ms) BEGIN
(0.1ms) ROLLBACK
Rendered pals/confirm.html.erb within layouts/application (1.8ms)
Completed 200 OK in 60ms (Views: 50.6ms | ActiveRecord: 1.1ms)
Started GET "/assets/access.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/bootstrap_and_overrides.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/pals.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/users.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-transition.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-alert.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-modal.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-dropdown.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-scrollspy.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-tab.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-tooltip.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-popover.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-button.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-collapse.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-typeahead.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-carousel.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:29 0000
Started GET "/assets/twitter/bootstrap/bootstrap-affix.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:30 0000
Started GET "/assets/twitter/bootstrap.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:30 0000
Started GET "/assets/turbolinks.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:30 0000
Started GET "/assets/pals.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:30 0000
Started GET "/assets/access.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:30 0000
Started GET "/assets/users.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:30 0000
Started GET "/assets/bootstrap.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:30 0000
Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2014-07-03 16:16:30 0000
Комментарии:
1. Вы можете отладить его, добавив @newuser.save! вместо @newuser.save, чтобы узнать об ошибке.
2. У вас есть
pal = Pal.find(params[:palid])
. этоpal
без@
. тогда у вас есть@newuser.username = @pal.phone
. очевидно,@newuser
неправильно определено. еслиpal
и@pal
не являются двумя разными переменными3. На самом деле это была опечатка при редактировании моего поста, у меня есть
@
в моем коде, проверьте обновления, чтобы узнать больше о моей проблеме, пожалуйста!
Ответ №1:
Если вы посмотрите на свой код
def confirm
pal = Pal.find(params[:palid]) # you have find your pal and store it in "pal"
@newuser = User.new(newuser_params)
@newuser.username = @pal.phone # you are using instance variable "@pal" which is not defined
# your other logic
end
Вместо этого у вас должен быть ваш код, подобный:
def confirm
@pal = Pal.find(params[:palid])
@newuser = User.new(newuser_params)
@newuser.username = @pal.phone
# your other logic
end
Также в вашей форме вы должны поместить этот код
<% if @newuser.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@newuser.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @newuser.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Это отобразит, есть ли какие-либо ошибки проверки в вашей форме. Для получения подробной информации обратитесь к here
Обновить:
Если вы посмотрите на параметры, которые передаются из вашей формы, обратите внимание на это
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8X6LD0g6E1HybdAF/FOlM09iuQLWExBY8dY5CqSDZsM=", "newuser"=>{"password"=>"[FILTERED]"}, "commit"=>"Save Newuser", "palid"=>"5"}
В вашей форме есть пара ошибок:
a. Либо вы не ввели свое имя пользователя в форму, либо вы неправильно создали свою форму, потому что в параметрах отображается только поле пароля "newuser"=>{"password"=>"[FILTERED]"}
б. Вы не разрешили свое поле пароля вместо разрешения пароля вы разрешили:password_digest, :password_stored. Ваши newuser_params должны выглядеть следующим образом:
def newuser_params
params.require(:newuser).permit(:username, :password)
end
c. что "palid"=>"5"
делает в ваших параметрах? Это поле в вашей форме или что, потому что оно не связано с параметрами newuser
Комментарии:
1. Насчет ‘@’ это была опечатка, она уже была у меня в коде, я потерял ее только во время копирования. Спасибо за отображение ошибки, это помогает, но там написано «Пароль не может быть пустым» , который не является пустым, я его пишу .. Пожалуйста, проверьте мое обновление.
2. @TECHPUSHTA можете ли вы публиковать свои журналы с параметрами при отправке формы?
3. Я уже опубликовал параметры, я полагаю.. Кажется, я не понял вашего вопроса.. Пожалуйста, объясните.
4. @TECHPUSHTA очистите свой терминал или консоль, а затем отправьте свою форму, после отправки в вашем терминале будет показано, какой запрос отправляется на сервер, и параметры, можете ли вы опубликовать это
5. @TECHPUSHTA рад, что смог помочь 🙂
Ответ №2:
Проверьте ошибки проверки в @newuser
, а именно @newuser.errors
. Существуют методы, которые пропускают проверки. Возможно, вы используете их в консоли.