20211126のRailsに関する記事は8件です。

railsチュートリアル第十三章 マイクロポストを作成する

マイクロポストを作成する Micropostsコントローラのcreateアクション app/controllers/microposts_controller.rb class MicropostsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] # create,destroyを行う前にログインを求めらえれる。 def create @micropost = current_user.microposts.build(micropost_params) # 慣習的に関連するモデルを生成するときは、buildを使う if @micropost.save flash[:success] = "Micropost created!" redirect_to root_url # redirect_to は、view の表示には直接は関係なく、新たな HttpRequest が発行されます。 else render 'static_pages/home' # action で view を指定しない場合、規約に従って、リソース名 や # action名を元に、表示する view が決まります。 end end def destroy end private def micropost_params params.require(:micropost).permit(:content) # マイクロポストのcontentカラムだけ取り出すことができる。 end end Homeページ(/)にマイクロポストの投稿フォームを追加する app/views/static_pages/home.html.erb <% if logged_in? %> <div class="row"> <aside class="col-md-4"> <section class="user_info"> <%= render 'shared/user_info' %> </section> <section class="micropost_form"> <%= render 'shared/micropost_form' %> </section> </aside> </div> <% else %> <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %> </div> <%#= image_tag("kitten.jpg", alt: "Kitten") %> <%= link_to image_tag("rails.svg", alt: "Rails logo", width: "200px"), "https://rubyonrails.org/" %> サイドバーで表示するユーザー情報のパーシャル app/views/shared/_user_info.html.erb <%= link_to gravatar_for(current_user, size: 50), current_user %> <!--グラバターの画像と何か--> <h1><%= current_user.name %></h1> <!--ユーザー名--> <span><%= link_to "view my profile", current_user %></span> <!--リンクとリンク先--> <!--current_user とは権限のチェックに使われるユーザー識別子--> <span><%= pluralize(current_user.microposts.count, "micropost") %></span> <!--マイクロポストの数を表示する--> <!--例 3micropost--> マイクロポスト投稿フォームのパーシャル app/views/shared/_micropost_form.html.erb <%= form_with(model: @micropost, local: true) do |f| %> <!--local: trueがない場合、Rails5ではAjaxによる送信という意味になる。 普通にHTMLとしてフォームを送信する場合にlocal: trueが必要になる--> <!--マイクロポストをHTMLのフォームとして一つずつ取り出す--> <%= render 'shared/error_messages', object: f.object %> <!--sharedフォルダのerror_messagesを表示させる。--> <!--object: f.objectでは、f.objectに@userが入っている--> <!--object: f.objectはerror_messagesパーシャルの中でobjectという変数名を 作成してくれるので、この変数を使って エラーメッセージを更新すればよいということです--> <div class="field"> <%= f.text_area :content, placeholder: "Compose new micropost..." %> <!--コメント欄を作ることができる--> <!--その欄にコメントを書いておく--> </div> <%= f.submit "Post", class: "btn btn-primary" %> <% end %> homeアクションにマイクロポストのインスタンス変数を追加する app/controllers/static_pages_controller.rb class StaticPagesController < ApplicationController def home @micropost = current_user.microposts.build if logged_in? # ログインされたら current_userのマイクロポストを生成する end def help end def about # aboutアクションを作成 end def contact end end Userオブジェクト以外でも動作するようにerror_messagesパーシャルを更新する app/views/shared/_error_messages.html.erb <% if object.errors.any? %> <div id="error_explanation"> <div class="alert alert-danger"> The form contains <%= pluralize(object.errors.count, "error") %>. <!--@user.errors.countはエラーの回数--> <!--pluralizeは引数が出力される--> <!--エラーの回数と"error"の文字列が表示される--> </div> <ul> <% object.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> テスト ubuntu:~/environment/sample_app (user-microposts) $ rails t Running via Spring preloader in process 9841 Started with run options --seed 3594 ERROR["test_password_resets", #<Minitest::Reporters::Suite:0x0000558f7e479e20 @name="PasswordResetsTest">, 3.4448097949998555] test_password_resets#PasswordResetsTest (3.45s) ActionView::Template::Error: ActionView::Template::Error: undefined local variable or method `object' for #<#<Class:0x0000558f7df2a370>:0x0000558f7e3a5fd0> Did you mean? object_id app/views/shared/_error_messages.html.erb:1 app/views/password_resets/edit.html.erb:8 app/views/password_resets/edit.html.erb:6 test/integration/password_resets_test.rb:49:in `block in <class:PasswordResetsTest>' ERROR["test_should_get_home", #<Minitest::Reporters::Suite:0x0000558f7e66cc50 @name="StaticPagesControllerTest">, 3.56740082899978] test_should_get_home#StaticPagesControllerTest (3.57s) ActionView::SyntaxErrorInTemplate: ActionView::SyntaxErrorInTemplate: Encountered a syntax error while rendering template: check <% if logged_in? %> <div class="row"> <aside class="col-md-4"> <section class="user_info"> <%= render 'shared/user_info' %> </section> <section class="micropost_form"> <%= render 'shared/micropost_form' %> </section> </aside> </div> <% else %> <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %> </div> <%#= image_tag("kitten.jpg", alt: "Kitten") %> <%= link_to image_tag("rails.svg", alt: "Rails logo", width: "200px"), "https://rubyonrails.org/" %> app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end test/controllers/static_pages_controller_test.rb:19:in `block in <class:StaticPagesControllerTest>' ERROR["test_should_get_root", #<Minitest::Reporters::Suite:0x0000558f7ec0bb98 @name="StaticPagesControllerTest">, 3.6514615249998315] test_should_get_root#StaticPagesControllerTest (3.65s) ActionView::SyntaxErrorInTemplate: ActionView::SyntaxErrorInTemplate: Encountered a syntax error while rendering template: check <% if logged_in? %> <div class="row"> <aside class="col-md-4"> <section class="user_info"> <%= render 'shared/user_info' %> </section> <section class="micropost_form"> <%= render 'shared/micropost_form' %> </section> </aside> </div> <% else %> <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %> </div> <%#= image_tag("kitten.jpg", alt: "Kitten") %> <%= link_to image_tag("rails.svg", alt: "Rails logo", width: "200px"), "https://rubyonrails.org/" %> app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end test/controllers/static_pages_controller_test.rb:12:in `block in <class:StaticPagesControllerTest>' ERROR["test_login_with_valid_email/invalid_password", #<Minitest::Reporters::Suite:0x0000558f7dd5b9b8 @name="UsersLoginTest">, 4.065607392999937] test_login_with_valid_email/invalid_password#UsersLoginTest (4.07s) ActionView::SyntaxErrorInTemplate: ActionView::SyntaxErrorInTemplate: Encountered a syntax error while rendering template: check <% if logged_in? %> <div class="row"> <aside class="col-md-4"> <section class="user_info"> <%= render 'shared/user_info' %> </section> <section class="micropost_form"> <%= render 'shared/micropost_form' %> </section> </aside> </div> <% else %> <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %> </div> <%#= image_tag("kitten.jpg", alt: "Kitten") %> <%= link_to image_tag("rails.svg", alt: "Rails logo", width: "200px"), "https://rubyonrails.org/" %> app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end test/integration/users_login_test.rb:19:in `block in <class:UsersLoginTest>' ERROR["test_login_with_valid_information_followed_by_logout", #<Minitest::Reporters::Suite:0x0000558f7e082740 @name="UsersLoginTest">, 4.221937290999904] test_login_with_valid_information_followed_by_logout#UsersLoginTest (4.22s) ActionView::SyntaxErrorInTemplate: ActionView::SyntaxErrorInTemplate: Encountered a syntax error while rendering template: check <% if logged_in? %> <div class="row"> <aside class="col-md-4"> <section class="user_info"> <%= render 'shared/user_info' %> </section> <section class="micropost_form"> <%= render 'shared/micropost_form' %> </section> </aside> </div> <% else %> <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %> </div> <%#= image_tag("kitten.jpg", alt: "Kitten") %> <%= link_to image_tag("rails.svg", alt: "Rails logo", width: "200px"), "https://rubyonrails.org/" %> app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end test/integration/users_login_test.rb:45:in `block in <class:UsersLoginTest>' ERROR["test_layout_links_when_logged_in", #<Minitest::Reporters::Suite:0x0000558f7edf52b0 @name="SiteLayoutTest">, 4.905898562999937] test_layout_links_when_logged_in#SiteLayoutTest (4.91s) ActionView::SyntaxErrorInTemplate: ActionView::SyntaxErrorInTemplate: Encountered a syntax error while rendering template: check <% if logged_in? %> <div class="row"> <aside class="col-md-4"> <section class="user_info"> <%= render 'shared/user_info' %> </section> <section class="micropost_form"> <%= render 'shared/micropost_form' %> </section> </aside> </div> <% else %> <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %> </div> <%#= image_tag("kitten.jpg", alt: "Kitten") %> <%= link_to image_tag("rails.svg", alt: "Rails logo", width: "200px"), "https://rubyonrails.org/" %> app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end test/integration/site_layout_test.rb:29:in `block in <class:SiteLayoutTest>' ERROR["test_layout_links", #<Minitest::Reporters::Suite:0x0000558f7c452b60 @name="SiteLayoutTest">, 4.953971497999646] test_layout_links#SiteLayoutTest (4.95s) ActionView::SyntaxErrorInTemplate: ActionView::SyntaxErrorInTemplate: Encountered a syntax error while rendering template: check <% if logged_in? %> <div class="row"> <aside class="col-md-4"> <section class="user_info"> <%= render 'shared/user_info' %> </section> <section class="micropost_form"> <%= render 'shared/micropost_form' %> </section> </aside> </div> <% else %> <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %> </div> <%#= image_tag("kitten.jpg", alt: "Kitten") %> <%= link_to image_tag("rails.svg", alt: "Rails logo", width: "200px"), "https://rubyonrails.org/" %> app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end app/views/static_pages/home.html.erb:28: syntax error, unexpected end-of-input, expecting end test/integration/site_layout_test.rb:6:in `block in <class:SiteLayoutTest>' 56/56: [===========================] 100% Time: 00:00:04, Time: 00:00:04 Finished in 4.96300s 56 tests, 265 assertions, 0 failures, 7 errors, 0 skips ActionView::Template::Error: ActionView::Template::Error: undefined local variable or method `object' ActionView::SyntaxErrorInTemplate: ActionView::SyntaxErrorInTemplate: Encountered a syntax error while rendering template: check <% if logged_in? %> と書かれている。 objectがおかしいのがわかる、その次がわからない このパーシャルは他の場所でも使われていたため、ユーザー登録、パスワード再設定、そしてユーザー編集のそれぞれのビューを更新する必要があったのです。 ユーザー登録時のエラー表示を更新する app/views/users/new.html.erb <% provide(:title, 'Sign up') %> <h1>Sign up</h1> <div class="row"> <div class="col-md-6 col-md-offset-3"> <%= form_with(model: @user, local: true) do |f| %> <!--一つずつ取り出す--> <%= render 'shared/error_messages', object: f.object %> <%= f.label :name %> <%= f.text_field :name, class: 'form-control' %> <%= f.label :email %> <%= f.email_field :email, class: 'form-control' %> <%= f.label :password %> <%= f.password_field :password, class: 'form-control' %> <%= f.label :password_confirmation, "Confirmation" %> <%= f.password_field :password_confirmation, class: 'form-control' %> <%= f.submit "Create my account", class: "btn btn-primary" %> <% end %> </div> </div> ユーザー編集時のエラー表示を更新する app/views/users/edit.html.erb <% provide(:title, "Edit user") %> <h1>Update your profile</h1> <div class="row"> <div class="col-md-6 col-md-offset-3"> <%= form_with(model: @user, local: true) do |f| %> <%= render 'shared/error_messages', object: f.object %> <%= f.label :name %> <%= f.text_field :name, class: 'form-control' %> <%= f.label :email %> <%= f.email_field :email, class: 'form-control' %> <%= f.label :password %> <%= f.password_field :password, class: 'form-control' %> <%= f.label :password_confirmation, "Confirmation" %> <%= f.password_field :password_confirmation, class: 'form-control' %> <%= f.submit "Save changes", class: "btn btn-primary" %> <% end %> <div class="gravatar_edit"> <%= gravatar_for @user %> <a href="https://gravatar.com/emails">change</a> </div> </div> </div> パスワード再設定時のエラー表示を更新する app/views/password_resets/edit.html.erb <% provide(:title, 'Reset password') %> <h1>Reset password</h1> <div class="row"> <div class="col-md-6 col-md-offset-3"> <%= form_with(model: @user, url: password_reset_path(params[:id]), local: true) do |f| %> <%= render 'shared/error_messages', object: f.object %> <%= hidden_field_tag :email, @user.email %> <!--隠しフィールドとしてページ内に保存する手法をとります。--> <!--フォームを送信した後使用するメアドが消えてしまうので   ここに保存させる。--> <%= f.label :password %> <%= f.password_field :password, class: 'form-control' %> <%= f.label :password_confirmation, "Confirmation" %> <%= f.password_field :password_confirmation, class: 'form-control' %> <%= f.submit "Update password", class: "btn btn-primary" %> <% end %> </div> </div> 演習 1.Homeページをリファクタリングして、if-else文の分岐のそれぞれに対してパーシャルを作ってみましょう。 home.html.erb <% if logged_in? %> <%= render 'static_pages/user_logged_in' %> <% else %> <%= render 'static_pages/user_not_logged_in' %> <% end %> user_logged_in.html.erb <div class="row"> <aside class="col-md-4"> <section class="user_info"> <%= render 'shared/user_info' %> </section> <section class="micropost_form"> <%= render 'shared/micropost_form' %> </section> </aside> </div> user_not_logged_in.html.rb <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="http://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %> </div> <%= link_to image_tag("rails.svg", alt: "Rails logo", width: "200px"), 'http://rubyonrails.org/' %> 2. マイクロポストを投稿した直後に、ブラウザの更新ボタンを押すとエラーが表示されます。なぜエラーが表示されるのでしょうか?その原因を考えてみましょう。 わからない。 3. もし上記の現象に対応するとしたら、どんな対応方法があるでしょうか?その対応方法を考えてみましょう。(ヒント: 様々な対応方法がありますが、対応方法によっては今後の実装に支障が出ることがあります。ここでは対応方法のアイデア出しに留めておきましょう。) わからない。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

railsチュートリアル第13章 マイクロポストを操作する

マイクロポストを操作する データモデリングとマイクロポスト表示テンプレートの両方が完成したので、次はWeb経由でそれらを作成するためのインターフェイスに取りかかりましょう。 インターフェース IT関連では、二つのものが接続・接触する箇所や、両者の間で情報や信号などをやりとりするための手順や規約を定めたものを意味する 最後に、ユーザーがマイクロポストをWeb経由で破棄できるようにします。 マイクロポストリソースのルーティング config/routes.rb Rails.application.routes.draw do . . . # /users/1の有効にするため resources :account_activations, only: [:edit] # editアクションへの名前付きルートが必要になるため # ルーティングのアカウント有効化 resources :password_resets, only: [:new, :create, :edit, :update] # 新しいパスワードを再設定するためのフォームと、Userモデル内のパスワードを変更するため resources :microposts, only: [:create, :destroy] # マイクロポストにはcreate,destroyあれば十分 # RESTfulなルーティングのサブセットになります。 # サブセットとは、一部分、部分集合、下位集合などの意味を持つ英単語 end HTTPリクエスト    URL    アクション   名前付きルート POST        /microposts    create    microposts_path DELETE       /microposts/1   destroy    micropost_path(micropost) マイクロポストのアクセス制御 Micropostsコントローラの認可テスト test/controllers/microposts_controller_test.rb require 'test_helper' class MicropostsControllerTest < ActionDispatch::IntegrationTest def setup @micropost = microposts(:orange) # サンプルのマイクロポスト end test "should redirect create when not logged in" do assert_no_difference 'Micropost.count' do # マイクロポストの数を数えて違いがないかを確認 post microposts_path, params: { micropost: { content: "Lorem ipsum" }} # マイクロポストを投稿する # contentカラムに"Lorem ipsum"と入力 end assert_redirected_to login_url # ログインページに転送 end test "should redirect destroy when not logged in" do assert_no_difference 'Micropost.count' do # マイクロポストの数に違いがないか? delete micropost_path(@micropost) # マイクロポストを削除 end assert_redirected_to login_url # ログインページに転送 end end logged_in_userメソッドをApplicationコントローラに移す app/controllers/application_controller.rb class ApplicationController < ActionController::Base include SessionsHelper private # クラスの外からは呼び出せない。 # 同じインスタンス内でのみ、関数形式で呼び出せる。 # ユーザーのログインを確認する def logged_in_user unless logged_in? # ログインされていないかどうか? store_location # session[:forwarding_url] = request.url if request.get? # アクセスしようとしたURLを覚えておく # request リクエストを送ってきたユーザのヘッダー情報や # 環境変数を取得 flash[:danger] = "Please log in." # ログインされていなかったらメッセージを送る redirect_to login_url # ログインページに送る end end end Usersコントローラ内のlogged_in_userフィルターを削除する app/controllers/users_controller.rb class UsersController < ApplicationController before_action :logged_in_user, only: [:index, :edit, :update, :destroy] . . . private . . . # 正しいユーザーかどうか確認 def correct_user @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) # データベースと照らし合わせて無かったらホーム画面にいく。 end # 管理者かどうか確認 def admin_user redirect_to(root_url) unless current_user.admin? #管理者でなければホーム画面に移動する end end Micropostsコントローラの各アクションに認可を追加する app/controllers/microposts_controller.rb class MicropostsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] # create,destroyを行う前にログインを求めらえれる。 def create end def destroy end end テスト ubuntu:~/environment/sample_app (user-microposts) $ rails t Running via Spring preloader in process 15532 Started with run options --seed 8815 56/56: [===========================] 100% Time: 00:00:04, Time: 00:00:04 Finished in 4.11320s 56 tests, 293 assertions, 0 failures, 0 errors, 0 skips 演習 1. なぜUsersコントローラ内にあるlogged_in_userフィルターを残したままにするとマズイのでしょうか? 考えてみてください。 わからなかった。 調べてみると コードが重複してしまうためらしい。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

railsチュートリアル第13章 プロフィール画面のマイクロポストをテストする

プロフィール画面のマイクロポストをテストする プロフィール画面で表示されるマイクロポストに対して、統合テストを書いていきます。 ubuntu:~/environment/sample_app (user-microposts) $ rails generate integration_test users_profile Running via Spring preloader in process 6991 invoke test_unit create test/integration/users_profile_test.rb 生成されたマイクロポストfixture test/fixtures/microposts.yml orange: content: "I just ate an orange!" created_at: <%= 10.minutes.ago %> user: michael # ユーザーfixtureにある対応ユーザーに関連付けることをRailsに指示できます。 tau_manifesto: content: "Check out the @tauday site by @mhartl: https://tauday.com" created_at: <%= 3.years.ago %> user: michael cat_video: content: "Sad cats are sad: https://youtu.be/PKffm2uI4dk" created_at: <%= 2.hours.ago %> user: michael most_recent: content: "Writing a short test" created_at: <%= Time.zone.now %> user: michael <% 30.times do |n| %> micropost_<%= n %>: content: <%= Faker::Lorem.sentence(word_count: 5) %> created_at: <%= 42.days.ago %> user: michael <% end %> Userプロフィール画面に対するテスト test/integration/users_profile_test.rb require 'test_helper' class UsersProfileTest < ActionDispatch::IntegrationTest include ApplicationHelper def setup @user = users(:michael) # テストユーザーを設定 end test "profile display" do get user_path(@user) # ユーザーページに行くを要求 assert_template 'users/show' # showアクションを表示されるか? # ユーザーページが表示されているか? assert_select 'title', full_title(@user.name) # ユーザーページのタイトルタグにユーザー名が表示されているか? assert_select 'h1', text: @user.name # h1タグにユーザー名が表示されているか? assert_select 'h1>img.gravatar' # h1タグ(トップレベルの見出し)の内側にある、gravatarクラス付きのimgタグがあるかどうかをチェックできます。 assert_match @user.microposts.count.to_s, response.body # response.bodyにはそのページの完全なHTMLが含まれています # そのページのどこかしらにマイクロポストの投稿数が存在するのであれば、 # 次のように探し出してマッチできる assert_select 'div.pagination' # ページネーションが表示されているか? @user.microposts.paginate(page: 1).each do |micropost| assert_match micropost.content, response.body # マイクロポストがあるかどうか? end end end テスト ubuntu:~/environment/sample_app (user-microposts) $ rails t Running via Spring preloader in process 8880 Started with run options --seed 3883 54/54: [============================] 100% Time: 00:00:09, Time: 00:00:09 Finished in 9.41028s 54 tests, 288 assertions, 0 failures, 0 errors, 0 skips 演習 1. リスト 13.28にある2つの'h1'のテストが正しいか確かめるため、該当するアプリケーション側のコードをコメントアウトしてみましょう。テストが green から red に変わることを確認してみてください。 ubuntu:~/environment/sample_app (user-microposts) $ rails t Running via Spring preloader in process 9267 Started with run options --seed 35939 FAIL["test_profile_display", #<Minitest::Reporters::Suite:0x000055f1ec686990 @name="UsersProfileTest">, 1.963515799000561] test_profile_display#UsersProfileTest (1.96s) <Michael Example> expected but was <>.. Expected 0 to be >= 1. test/integration/users_profile_test.rb:19:in `block in <class:UsersProfileTest>' 54/54: [============================] 100% Time: 00:00:02, Time: 00:00:02 Finished in 2.55123s 54 tests, 224 assertions, 1 failures, 0 errors, 0 skips 2. リスト 13.28にあるテストを変更して、will_paginateが1度のみ表示されていることをテストしてみましょう。ヒント: 表 5.2を参考にしてください。 assert_select 'h1>img.gravatar' # h1タグ(トップレベルの見出し)の内側にある、 # gravatarクラス付きのimgタグがあるかどうかをチェックできます。 assert_match @user.microposts.count.to_s, response.body # response.bodyにはそのページの完全なHTMLが含まれています # そのページのどこかしらにマイクロポストの投稿数が存在するのであれば、 # 次のように探し出してマッチできる assert_select 'div.pagination' # ページネーションが表示されているか? assert_select 'div.pagination', count:1 @user.microposts.paginate(page: 1).each do |micropost| assert_match micropost.content, response.body # マイクロポストがあるかどうか? end end end <%= will_paginate renderer: BootstrapPagination::Rails %> とすると ページネーションのスタイルが変わるらしい。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

M1でrails db:createが出来ない no suitable image found. Did find: (LoadError)諸々

M1でのrailsアプリ環境構築方法についてはこちらでまとめています。 環境 rbenv 1.2.0 ruby 3.0.2 Bundler 2.2.32 yarn 1.22.17 DBはpostgresql rails db:createが出来ない問題 rails db:createをすると このようなエラーが大量発生してしまいました。 no suitable image found. Did find: (LoadError)とあります。 何かがないのでしょう。(かなり曖昧) 対処法 arch -arm64 gem install msgpack bootsnap bindex zeitwerk activesupport spring webpacker railties rack thor nio4r puma bootsnap activesupport ffi でインストールし直すとrails db:createが成功しました。 M1で出てしまうエラーなのか、もしくは私のMacがいけないのかわかりませんが 同じようなエラーで悩まれている方がいたら参考にしてください!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

rails 個人的 初学者におすすめな記事

はじめに 今回は僕がrails初学者の時に(いまでも)よく参考にしていた記事を紹介します。 ぜひrails初学者のみなさんも参考にしてください!超おすすめです! ちなみに今回はうっす〜い内容です。 では見ていきましょう! 用語やコードの意味を調べたい時 こちらのサイトはプログラミングの用語をめちゃめちゃわかりやすく説明してくれています。 例えば、「paramsってなんや?」「データを扱うメソッド(whereとかfindとか)ってどうやって使うの?てかそもそもなんやねん!」ってことありませんか? そんな時にこのPikawakaさんではめちゃめちゃわかりやすく説明してくれています! さらに調べたものの関連した内容も記載してくれている時もあるので必要としていた以上の知識が得られます! 特定の機能を調べたい時 こちらのサイトはrailsのいろいろな機能などに関してわかりやすく説明してくれています。もともとプログラミングの講師をやっていた方が作っているので非常にわかりやすいです。 例えば、「SNS認証ってどうやるんやろ?」「非同期通信のいいね機能を実装したい!」といったような際に便利です! こちらのサイトは実際に実装できるコードとともに説明してくれているのでほとんどコピペしちゃえば実装できます。 よくある、「記事通りにやったねんけどエラーなったなあ〜」っていうのが今のところ全くないです! 最後に 僕はとにかくこの二つのサイトに助けられました! おそらくこれからもちょくちょくお世話になるとは思います。それくらい信頼しています! この記事を見ていただいたみなさんもぜひこれらのサイトを見てみてください。 世界変わります!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

rails Googlemapエラー集

はじめに こんにちは。 とあるスクールで長めにメンターやってたもんです。 プログラミングってほんのちょっとの間違いでエラーになっちゃうから初心者の人は辛いですよね〜 今回は生徒さんのwebアプリ開発でようでる、Mapがでない・うまく表示されない問題がよくあるので、今後のメンターさんや生徒さんがちょっとでも楽になりますように。 ※注意:エラーやうまいこといかんのを自分で解決する楽しさは奪いたくないのでほんまに無理な時に見てください。 開発環境でのエラー 1.そもそも地図が表示されるはず部分のスペースがない これはhtml・cssでのミスがあると考えられます。 例えば、 2. cssの書き忘れ 3. id名あるいはclass名とセレクタ名が一致していない これらが多いかと思います。 2.マップを表示するためのスペースはあるがマップは表示されず空白になっている。 こちらすごく多いです。なので原因もたくさんあります。 考えられる限りの原因を記していきますね。 1. id名とgetElemmentByIdの名前が一致していない。 2. .envファイルへの記述が間違っている。(そもそも.envファイルを使ってない人はデプロイする前に大事なものは.envファイルに転記しときましょう) 3. geocoder. rbの記述が間違っている。とくにAPIを書く部分。 4. scriptタグ内の記述ミス(ここはJSを書いたことのない人にはむずかしいかも)。 とくによく見るのは、カッコの閉じ忘れやmarkerやinfowindowの部分。 5. データの受け渡しミス。(緯度、経度から住所を出す場合など) 3.マップはでているが、「このページではGoogleマップが正しく読み込まれませんでした。」というメッセージがでていてマップが正しく表示できない。 この場合の原因は基本的に一つです。 GCPでクレジットカードの登録ができていないことが原因のほとんどです。 なのでGCPにクレジットカードの登録をしましょう! その際、APIの割り当てをお金がかからないところに設定しときましょう!そうすればお金をとられることはありません。 herokuデプロイ中・後のエラー
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Rails] AWS SESのSMTPサーバを使う大まかな流れとSandboxを解除したやりとりの記録

Deviseのパスワード発行メールのように、返信を気にしないメールをサクッと飛ばしたい時がままあるので記事にしました。 Rails gem gem 'aws-sdk-rails' ActionMailer # config/initializers/aws.rb Aws::Rails.add_action_mailer_delivery_method( :ses, credentials: Aws::Credentials.new(ENV.fetch('AWS_ACCESS_KEY_ID') { 'AWS_ACCESS_KEY_ID' }, ENV.fetch('AWS_SECRET_ACCESS_KEY') { 'AWS_SECRET_ACCESS_KEY' }), region: 'ap-northeast-1' ) # config/environments/production.rb config.action_mailer.delivery_method = :ses AWS IAM ユーザグループにSESのPermission policy を追加する IAM > User groups SES ドメインの所有者確認とDKIM認証してもらう Amazon Simple Email Service Sandboxの解除リクエスト その後 リクエストの詳細確認の連絡が届いたので、回答したところ無事解除されました?(というか日本語でもよかったかも) Good day, thank you to confirm our request. We respond to enhance information. I wonder if you could look at that. Thanks. how often you send email: Less than 5 email a month. how you maintain your recipient lists: The administrator can regulate at the web site who will receive mail. your website or app(please include any necessary links): Website URL: https://www.example.com how you manage bounces, complaints, and unsubscribe requests: Only colleague obtains mail. If the member cannot receive a mail, who can ask the administrator. It is also helpful to provide examples of the email you plan to send so we can ensure that you are sending high-quality content: Subject: Reset password instructions Body: Hello <%= @resource.email %>! Someone has requested a link to change your password. You can do this through the link below. <%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %> If you didn't request this, please ignore this email. Your password won't change until you access the link above and create a new one. Hello, Thank you for submitting your request to increase your sending limits. We are unable to grant your request at this time because we do not have enough information about your use case. If you can provide additional information about how you plan to use Amazon SES , we may be able to grant your request. In your response, include as much detail as you can about your email-sending use case and how you intend to use Amazon SES. For example, tell us more about how often you send email, how you maintain your recipient lists, your website or app(please include any necessary links), and how you manage bounces, complaints, and unsubscribe requests. It is also helpful to provide examples of the email you plan to send so we can ensure that you are sending high-quality content. You can provide this information by replying to this message. Our team provides an initial response to your request within 24 hours. If we're able to do so, we'll grant your request within this 24-hour period. However, if we need to obtain additional information from you, it might take longer to resolve your request. Thank you for contacting Amazon Web Services. We value your feedback. Please share your experience by rating this correspondence using the AWS Support Center link at the end of this correspondence. Each correspondence can also be rated by selecting the stars in top right corner of each correspondence within the AWS Support Center. 参考になりました?
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Railsのセットアップの時、mysql2というgemのせいでbundle installができない時に見る記事

概要 Rails + MySQLで開発環境を構築する際に発生しうるそこそこややこしいエラーについて、自分なりにまとめてみました。 ※Railsの中で、mysql2というgemを使用してます。 発生したエラーについて Railsのプロジェクトをrails newコマンドで作成後、bundle installした際に下記のエラーが発生することがある。 ...省略 Gem::Ext::BuildError: ERROR: Failed to build gem native extension. ...省略 linking shared-object mysql2/mysql2.bundle ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [mysql2.bundle] Error 1 make failed, exit code 2 Gem files will remain installed in /var/folders/mj/93db0vd975799gg9w3nnr3_r0000gn/T/bundler20190503-14531-xlyd6cmysql2-0.5.2/gems/mysql2-0.5.2 for inspection. Results logged to /var/folders/mj/93db0vd975799gg9w3nnr3_r0000gn/T/bundler20190503-14531-xlyd6cmysql2-0.5.2/extensions/universal-darwin-18/2.3.0/mysql2-0.5.2/gem_make.out An error occurred while installing mysql2 (0.5.2), and Bundler cannot continue. Make sure that `gem install mysql2 -v '0.5.2'` succeeds before bundling. In Gemfile: mysql2 このエラーメッセージで着目したいのは、この一行である。 ld: library not found for -lssl これはどうやらopensslというライブラリに起因するエラーのようです。 (※厳密にはlibsslだそうです、、、) このlibsslは、どうやらGCC(GNU Compiler Collectionの略称)のopensslへのリンクオプションらしいです。(参照元) いろんな記事にて、 $ bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/openssl/lib" このコマンドを実行すると解決する!!!みたいなことがよく書かれていると思いますが、これは上記のopensslのライブラリの場所を--with-ldflagsというオプションに渡してあげるとopensslというライブラリ自体を参照するようにしてくれるみたいです。 ですが残念ながら、これでもまだ解決できないケースがあります。 引用元 MacのHigh Sierraから、デフォルトのOpenSSLがOpenSSLからLibreSSLになっているそうで、OpenSSLの諸々の問題を鑑みれば英断らしいのですが、そうはいっても開発環境の様々なツールがOpenSSLに依存しておりアレコレと新たな問題を引き起こすため、様々なツールのほうがLibreSSLに対応するまでさくっとOpenSSLに出戻る方法が下記です。 要するに、どうやらHigh Sierra以降はデフォルトがopensslになっていないそうです。 故に、冒頭にあったopensslというライブラリへの参照が見つからないみたいなエラーが発生してしまいます。 実際にOpenSSLのバージョンを覗いてみると、、、 $ openssl version LibreSSL 3.0.0 7 このようにLibreSSLになってしまっているそうですね、、、、、 この問題の解決方法として、opensslでデフォルトのLibreSSLからOpenSSLに変更する必要があります。 このやり方に関してはシンプルにパスを通すだけで良いそうです。 $ echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.zsh_profile ターミナルを再起動すると下記のように、OpenSSLに変更することができました。 $ openssl version OpenSSL 3.0.0 7 sep 2021 ここまでできたらbundle installコマンドが正常に動作すると重います!!! まとめ MySQLのセッティング周りはわりかしややこしいところが多くて、脳死しながらエラー解決しがちになってしまいますが、そこは堪えてエラーメッセージを一つづつ丁寧に読んでみましょう。 なんだかんだ、それがエラー解決の近道だったりしますよね (自戒の意味も込めて)。 参考記事一覧 bundle installでmysql2がエラーになる件 (Qiita) macでmysql2がbundle installできない時 (Qiita) macOS High Sierra(OSX)のOpenSSLをデフォルトのLibreSSLからOpenSSLに変更する (Qiita)
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む