###### tags: `rails` `controller` `form` # railsで使用する基本的形まとめ ## Rails コントローラー基本形 - ストロングパラメータは下記のようにupdate, createのときのみ使用します。 <details> <summary>コード例を参考に見る。(クリックするとソースが展開します。)</summary> ```ruby= def index @xxxs = Xxx.all end def new @xxx = Xxx.new end def show @xxx = Xxx.find_by(id: params[:id]) end def edit @xxx = Xxx.find_by(id: params[:id]) end # ストロングパラメータを使います def update @xxx = Xxx.find_by(id: params[:id]) if @xxx.update_attributes(xxx_params) end # ストロングパラメータを使います def create @xxx = Xxx.new(xxx_params) if @xxx.save redirect_to root_path end end private def xxx_params params.require(:xxx).permit(:yyy, :mmm) end ``` </details> ## rails form_for 基本形 ```rails= <%= form_for @post , url: {controller: :posts, action: :create} |f| %> <%= f.label :title %> <%= f.text_field :title %> <%= f.label :content %> <%= f.text_field :content %> <%= f.submit "決定" %> <% end %> ``` form_forの場合は、コントローラーで初期化したインスタンス変数を利用して、テーブルで定義されているカラム名を利用して効率的にhtmlを表現できます。 `f.label` or `f.text_field`に関してはform_forのヘルパーになりますので、下記参考にしてください。 [フォームヘルパーの種類と例](https://qiita.com/Hal_mai/items/1e5afd0c99dd9059839f) ## rails form_tag 基本形 ```rails= <%= form_tag( '/create' , method: :post )do %> <label>Title</label> <input type='text' name='post[title]'> <label>Content</label> <input type='text' name='post[content]'> <input type='submit' value='決定'> <% end %> ``` ## routes.rbの書き方 基本形 ```ruby= root 'xxx#yyy' # get '/' => 'xxxs#yyy' get '/new', to: 'xxxs#new', as: 'new' # get '/new' => 'xxxs#new' post '/create', to: 'xxxs#create', as: 'create' # post '/create' => 'xxxs#create' patch '/update/:id', to: 'xxxs#update', as: 'update' # patch '/update/:id' => 'xxxs#update' ``` よく使われない例に関してはコメントアウト化しております。 適宜使いやすい書き方で書いて頂ければいいですが、名前付きルートが好ましいと感じます。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up