Skip to content

Instantly share code, notes, and snippets.

@hamichamp
Created June 12, 2014 14:17
Show Gist options
  • Save hamichamp/2f40dc358d09dec35306 to your computer and use it in GitHub Desktop.
Save hamichamp/2f40dc358d09dec35306 to your computer and use it in GitHub Desktop.
Rails4でcollection_check_boxesを使って、多対多の関連をチェックボックスで設定する ref: http://qiita.com/hamichamp/items/8cf980e6d5ca9fd7e96f
...
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :authors %><br />
<%= collection_check_boxes(:post, :author_ids, Author.all, :id, :name) do |b| %>
<%= b.label { b.check_box + b.text } %>
<% end %>
</div>
...
class Author < ActiveRecord::Base
has_many :author_posts
has_many :posts, :through => :author_posts
end
rails g scaffold post title:string
rails g scaffold author name:string
rails g scaffold author_post post:references author:references
rake db:migrate
rails s
class Post < ActiveRecord::Base
has_many :author_posts
has_many :authors, :through => :author_posts
end
class PostsController < ApplicationController
...
def post_params
params.require(:post).permit(:title, {:author_ids => []})
end
...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment