deviseのカラム追加-Ruby on Rails-

Hey, guys:)
最近Deviseっていうgemを使ってログイン機能を開発中のアプリに追加させた。めっちゃ便利でやれることも盛り沢山!

しかし!!

なぜユーザーの名前を登録できるカラムがないのだ!!デフォルトで搭載されているはずじゃ…

もやもやしながらもnameを追加させたのでここで共有してみる。

バージョンはRails 5 向けです。

まずは皆さんお馴染みのmigrationから

$ bin/rails g migration AddNameToUsers name:string

それでもちろんrakeだね

$ rake db:migrate

はい、追加出来たね!

しかし!これだけでは終われない!!

新規ユーザー登録画面でユーザー名を登録できるようにする。

ファイル:app/views/devise/registrations/new.html.erb

<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div class = "field">
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true %>
  </div>   #この4行だけ追加、それ以外はデフォルトで書かれてるので以下省略

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
                          :
                          :

この時、デフォのコードを真似してf.name_field :nameみたいな調子乗った記述をしないように!(実体験。自らドブにハマりました..)

次のコードを追加するの忘れずに!!

ファイル;app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?  
  
  protected

  def configure_permitted_parameters
    added_attrs = [:name, :email, :password, :password_confirmation, :remember_me]
    devise_parameter_sanitizer.permit :sign_up, keys: added_attrs
    devise_parameter_sanitizer.permit :account_update, keys: added_attrs
  end
end

以上!!

Railsのバージョンが違うと最後のapplication_controller.rbに書く記述が変わってくるので注意してください。

See ya!!

nil?, empty?とblank?の違い-Ruby on Rails-[和訳]

hey, guys:)
nilとemptyとblankって一緒じゃないの?とふと疑問に思ってstack overflowで検索。。
なるほど〜,と思う説明があったので和訳してみる。この記事は質問者に770,回答者に1054のいいねがついているので良記事に違いない。
それでは和訳してみる。

–質問–

I find myself repeatedly looking for a clear definition of the differences of nil?, blank?, and empty? in Ruby on Rails.

私は何回もRuby on Railsnil?,blank?とempty?について明白な定義がないか探している。

–回答–

.nil? can be used on any object and is true if the object is nil.

.nil?はどんなオブジェクトに使えて、オブジェクトがnilならtrueを返す。

.empty? can be used on strings, arrays and hashes and returns true if:

.empty?は文字列(string)、配列(array)やハッシュ(hash)に使えて、例えば次のような時はtrueを返す;

String length == 0  
Array length == 0
Hash length == 0  

Running .empty? on something that is nil will throw a NoMethodError.

何かnilのものに.empty?をを使うとNoMethodErrorになってしまう。

That is where .blank? comes in.

その場合はblank?が使われるところだ。

It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.

.empty?が文字列、配列やハッシュで使われるのと同じようにRailsで実装できる。

nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
0.blank? == false

.blank? also evaluates true on strings which are non-empty but contain only whitespace:

.blank?は空白スペースの文字列にtrueを返す:

"  ".blank? == true
"  ".empty? == false

Rails also provides .present?, which returns the negation of .blank?.

Rails.blank?の否定を返す.present?を用意している。

Array gotcha: blank? will return false even if all elements of an array are blank.

.blank?は配列のすべての要素が空の場合であってもfalseを返す。

To determine blankness in this case, use all? with blank?, for example:

この場合、空か判断するにはall?blank?を一緒に使おう、例えば:

[ nil, '' ].blank? == false
[ nil, '' ].all? &:blank? == true 

これは覚えなきゃいけないのかな? 使う時にわからなくなったらまたこの記事をみるとしよう!
この記事のリンクに素敵な表があったからよかったらチェックしてみてね!
see you!!

A concise explanation of nil v. empty v. blank in Ruby on Rails - Stack Overflow

コントローラー名とモデル名の変更手順-Ruby on rails-

Hi:) When it’t time to blog, I translate and learn.
ということで今日もStack over flowの記事から抜粋。
記事表題は「How to rename rails controller and model in a project
(railsのプロジェクトでとうやったらコントローラ名とモデル名を変更するのか)」
です。
それでは記事を翻訳してみよう。

質問

I would like to rename a controller and the associated model:

コントローラー名と関連するモデル名を変更したい。

I wanted to change the Corps controller to Stores and the same (without final s) for the model.

CorpsコントローラーをStoresコントローラーに変えたく、モデルも(語尾のsを省いて)同様に名前を変えたいんだ。

Looking on google, people suggested to destroy and then generate again the controller and model. The problem is that it will erase the actual code of each files!

ググってみたが、一度消してからまたコントローラーとモデル作るように提案されたんだ。
けれども、記述したコードを消したくないんだ!

Any solution?

何か解決策はあるかな?

回答

Here is what I would do:

私のやりかたはこれだ;

Create a migration to change the table name (database level). I assume your old table is called corps. The migration content will be:

テーブル名(データベースも)を変更する為にmigrationを作る。君の古いテーブル名はcorpsだろう。
migrationの中身はこうであろう。

class RenameCorpsToStores < ActiveRecord::Migration
  def change
    rename_table :corps, :stores
  end
end

Change your model file name, your model class definition and the model associations:

モデル名とクラス名とモデルに関連付けされるものを変更しよう。

File rename: corp.rb -> store.rb  
  
# ファイル名変更:corp.rb -> store.rb  
  
Code of store.rb: Change class Corp for class Store  
  
# store.rb内のclass Corpをclass Storeに  
  
Rename all the model associations like has_many :corps -> has_many :stores  
  
# モデルに関連したものを全て変更。例えばhas_many:corps -> has_many:stores

Change your controller file name and your controller class definition:

コントローラーのファイル名とクラス名を変更しよう。

File rename: corps_controller.rb -> stores_controller.rb  
  
# ファイル名変更 : corps_controller.rb -> stores_controller.rb  
  
Code of stores_controller.rb: Change class CorpsController for class StoresController  
  
# stores_controller.rb内のclass CorpsControllerをclass StoresControllerに  
  
Rename views folders. From corps to stores.  
  
# ビューのフォルダ名もcorpsからstoresに変更

Make the necessary changes in paths in the config/routes.rb file, like resources :corps -> resources :stores, and make sure all the references in the code change from corps to stores (corps_path, …)

config/routes.rb内の必要なパス名を変更する。例えばresources :corpsresources :storesに。
corpsをstoresに変えたか注意深く確認しよう。(corps_path,…)

Remember to run the migration :)

migrationを実行するのを忘れないでね:)

If previous is not possible, try to delete the db/schema.rb and execute:

もし上記のやり方で上手く行かなかったら、db/schema.rbを削除して次を実行しよう。

 $rake db:drop && rake db:create && rake db:migrate

終    

かなり無難なやり方って感じw
でもこの回答に118のいいねが付いているので結構な賛同を得ているやり方のようだ。
私も実際にこれやってみて、vim:%s/corps/stores/gみたいにやればあっさりcontroller名とmodel名を変えることができた。

See you!!

リンク How to rename rails controller and model in a project - Stack Overflow

Everything is an object-全てはオブジェクト-RubyMonkより[Ruby][和訳]

Hey guys:)
早速だけど今日も和訳をするぜ!今日の記事は残念ながらstack over flowからのものではない。
Railsの公式チュートリアルRubyの勉強できるサイトのリンクがいくつか貼ってあったので、
そこからみつけたRubyMonkっていうところから抜粋してみた。
まだオブジェクト指向に馴染めていないのでまず基本的なオブジェクトとは?のところに注目してみた。
ただし、今回訳すのは導入部分のみです。この導入部分で続きが気になったら下のリンクから続きを参照願います。

–タイトル:Everything is an object(全てはオブジェクトである)–

In Ruby, just like in real life, our world is filled with objects.

Rubyは現実世界と同様にオブジェクトで溢れている。

Everything is an object - integers, characters, text, arrays - everything.

全てはオブジェクトである。整数、文字、 文、 配列のように全てだ。

To make things happen using Ruby, one always puts oneself in the place of an object and then has conversations with other objects, telling them to do stuff.

Rubyを使うのなら機能を持たせたオブジェクトを作り、その作られたオブジェクトが他のオブジェクトに命令を与えさせるようにするんだ。

Roleplaying as an object in your program is an integral part of object-oriented programming.

自分のプログラミングでオブジェクトを機能させるのはオブジェクト指向プログラミングには欠かせないものである。

To know which object you are at the moment, one may use the keyword self.

どのオブジェクトを現在使っているか知るには、selfというキーワードを使おう。

Try it for yourself.

自分でやってみよう。

(補足)
  
[1] pry(main)> self
=> main

As you can see, if you don’t specify which object you are, you automatically play the role of the main object that Ruby provides us by default.

君がみたように、どのオブジェクトを使っているか明記しなければ自動的にmainオブジェクトを使っていることになっている。これはRubyがデフォで搭載したものだ。

どうでしょう??
これはまだオブジェクト指向について完全に説明されてないが、
記事によって説明の仕方が大分異なったりするので取っ付きやすいと思ったら下のリンクからどうぞ。

See you:)

RubyMonk - Ruby Primer - Introduction to Objects

配列の中に値が入っているか確認[和訳]

hey, guys :)
さて、今日も和訳すっか!
今回は質問者に859、回答者に1331のいいね!がついている人気の記事である。
そんなにいい質疑応答だったのか!?って気になるよね。

ーー質問ーー

I have a value ‘Dog’ and an array [‘Cat’, ‘Dog’, ‘Bird’].

訳)'Dog'という値と[‘Cat’, ‘Dog’, ‘Bird’]の配列がある。

How do I check if it exists in the array without looping through it? Is there a simple way of checking if the value exists, nothing more?

どうやったらループしないで値が配列に入っているか確認できるんだ?シンプルに確認できないか?

ーー回答ーー

You’re looking for include?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

訳)君が探しているのはinclude?だ。

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

–終わり–

え?これだけ?w
いいね!が多い記事は難しい話に突っ込むようなイメージがあったが、シンプルなのが意外に明白で評判いいのかもしれない。

この記事を読んだ時最初は拍子抜けだったが、あっさりすぎて次第にエンジニア初心者の私に勇気を与えてくれているような気がした。

ありがとう、user211662(質問者)とBrian Campbell(回答者)。君たちのあっさりさは人に勇気を与えた。

Thank you user211662 and Brian Campbell. Your simplenesses are giving me a hope and courage.
Hope you two will check my blog someday. God bless you.

end

原文

Check if a value exists in an array in Ruby - Stack Overflow

Rubyのattr_accessorって何?[和訳]

hey guy:) 前回から引き続きstackoverflowの記事を共有したいなと思ったので和訳してみた。
こちらの記事は質問者に697、回答者に1691の"いいね"されている。基本的な質問かもしれないけど読みたくなるよね!

–質問–
I am having a hard time understanding attr_accessor in Ruby.
Can someone explain this to me? I have done tons of Google searches.
I just can’t understand it fully.

訳)Rubyのattr_accessorってなんやねん。誰か説明してくれへんか?ググってもみつからへんわ〜。理解できへん。

–回答–

Let’s say you have a class Person.

Personクラスがあったとしよう。

class Person
end

person = Person.new
person.name # => no method error

Obviously we never defined method name.

明らかにnameメソッドを定義していない。

Let’s do that.

定義してみよう。

class Person
  def name
    @name # simply returning an instance variable @name
  end
end

person = Person.new
person.name # => nil
person.name = "Dennis" # => no method error  

Aha, we can read the name, but that doesn’t mean we can assign the name.

よし、nameメソッドを読み込めた。だが名前を割り当てたわけではない。

Those are two different methods.

2つの別なメソッドがある。

Former called reader and latter called writer.

前者はreaderを後者はwriterを読み込んでいる。

We didn’t create the writer yet so let’s do that.

まだ記述されていないwriterを書いてみよう。

class Person
  def name
    @name
  end

  def name=(str)
    @name = str
  end
end

person = Person.new
person.name = 'Dennis'
person.name # => "Dennis"

Awesome. Now we can write and read instance variable @name using reader and writer methods.

よっしゃ。ついにreaderとwriterメソッドを使うことによってインスタンス変数(@name)を定義して呼び出すことができた。

Except, this is done so frequently, why waste time writing these methods every time?

これはよく使われる。だが、毎回こんなに記述するって時間もったいないと思わないかい?

We can do it easier.

もっと簡単にすることが出来るんだ。

class Person
  attr_reader :name
  attr_writer :name
end

Even this can get repetitive. When you want both reader and writer just use accessor!

まだ面倒くさい感じに書かれている。もしreaderとwriterを同時に書くならaccessorを使おう!

class Person
  attr_accessor :name
end

person = Person.new
person.name = "Dennis"
person.name # => "Dennis"

Works the same way!

同じ結果が返ってきた!

And guess what: the instance variable @name in our person object will be set just like when we did it manually, so you can use it in other methods.

考えてみて。インスタンス変数(@name)はpersonオブジェクトに設定することが出来る。先程私達が頑張ってやったように。
なのでそのオブジェクトを他のメソッドからも呼び出せるよ。

class Person
  attr_accessor :name

  def greeting
    "Hello #{@name}"
  end
end

person = Person.new
person.name = "Dennis"
person.greeting # => "Hello Dennis"

That’s it. こんな感じ。  

追記)readerとwriterはそれぞれゲッター、セッターと呼ばれている。

なるほど〜。実際にターミナルで試した方が感動する!
元となるコードから辿っていくのっておもしろいね!

See you!!:)

リンク

What is attr_accessor in Ruby? - Stack Overflow

Rubyのシンボルとは[和訳]

hi, long time not to see you guys:)

Rubyのハッシュってコードの書き方はわかるんだけど、いまいちピンとこない。
stackoverflowで調べてみてなんとなくわかったような気がした回答があったので和訳してみた。

–質問–

patient1 = { :ruby => "red" }
patient2 = { :ruby => "programming" }

patient1.each_key {|key| puts key.object_id.to_s}
3918094
patient2.each_key {|key| puts key.object_id.to_s}
3918094

上記のコードってどういう意味があるんだ?

–回答–
The symbol :ruby does not contain “red” or “programming”.

シンボル:rubyに"red"と"programming"という文字列はもたない。

The symbol :ruby is just the symbol :ruby.

シンボル:rubyはただのシンボル:rubyである。

It is your hashes, patient1 and patient2 that each contain those values, in each case pointed to by the same key.

それは君が作ったハッシュでpatient1とpatient2はそれぞれにバリューを持っている。それぞれの事象であればハッシュは同じキーを示している。

Think about it this way: If you go into the living room on christmas morning, and see two boxes with a tag on them that say “Kezzer” on them.
こう考えてみよう。もしあなたがクリスマスの朝にリビングルームへ行ったとしよう。そこには2つの箱があって、それぞれに"Kezzer"と書かれているタグがついている。

One has socks in it, and the other has coal.

片方には靴下が入っていて、もう片方には木炭が入っている。

You’re not going to get confused and ask how “Kezzer” can contain both socks and coal, even though it is the same name.

靴下と木炭がそれぞれの箱に入っているが、同じ名前である"Kezzer"タグが付いていても混同しないだろう。

Because the name isn’t containing the (crappy) presents.

なぜなら名前それ自体には(くだらない)プレゼントが含まれていないからだ。

It’s just pointing at them.   

名前はただそれらを示しているだけにすぎない。

Similarly, :ruby doesn’t contain the values in your hash, it just points at them.

同様に、:rubyは貴方が記述した値はハッシュに含まれない。ただ示しているだけだ。

はは
なんかオシャレな例えだねw See you :)

記事)

Understanding Symbols In Ruby - Stack Overflow