LoginSignup
8
9

More than 5 years have passed since last update.

has_manyとbelongs_toについて。モデルの関連付けされたformの作り方

Last updated at Posted at 2016-02-19

まずuserモデルに関連付けるpostモデルを作成する

$ rails g model Post content:text user:references

referencesオプションはモデルと関連付けるときに使うやつで、関連付けたいモデルを指定することで(今回はuserが指定してある)勝手にpostモデルに外部キー(user_id)のカラムを作成してくれる。
このジェネレートの時に
user_id:referencesとしてしまうと、postカラムuser_id_idが追加されてしまうから注意。
userと指定するだけでuser_idとrailsが勝手に判断してくれる。

userモデルにhas_manyを追加

もうpostモデルにはbelongs_to userが勝手に指定されているのでuserモデルのみにこれを加える

user.rb
has_many :posts

これで、userとpostが関連づいた。

postのルーティングを設定

routes.rb

  resources :users 
  resources :posts, :only => [:create, :destroy]

postはcreateとdestroyしか使わないからonlyオプションで限定する。

postコントローラーを作成

$ rails g controller posts

postコントローラーにcreateメソッドを作成

posts_controller.rb

def create
    @post = current_user.posts.build(post_params)
    if @post.save
      redirect_to current_user
    else
      render root_path
    end
  end

buildを使うとどのuserがpostしたかを勝手に関連付けてくれる。

form_forの作成

私はユーザー詳細ページであるusers/show.html.erbでformを作った。

show.html.erb

<%= form_for(@post) do |f| %>

  <%= f.label :content, "ひとこと" %>
  <%= f.text_area :content %>
  <%= f.submit "つぶやく"%>
<% end %>


これでもエラーが出る。
それはこのshowページがuserのshowアクションだから。
なのでusers_controller.rbのshowアクションにも追加をする。

users_controller.rb

def show
    @user = User.find(params[:id])
    @post = current_user.posts.build if logged_in?
  end


formのすぐ下に表示

show.html.erb

<% @user.posts.each do |p| %>
  <p>
    <%= p.content %>
  </p>
<% end %>

あとはcssで自分の好きなデザインにしておしまい。

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9