###Rails5.1.4にて、チェックボックスの値を表示できるようにしたいです。
理想としては
氏名:田中太郎
ポジション:キャッチャー ファースト セカンド
選手紹介: ○○○○○○○○○○
の「ポジション」をcheck_boxを使って取得し、viewで表示できるようにしたいです。
memberテーブル
class CreateMembers < ActiveRecord::Migration[5.1] def change create_table :members do |t| t.string :name t.string :position t.text :introduction t.timestamps end end end
positionテーブル
class CreatePositions < ActiveRecord::Migration[5.1] def change create_table :positions do |t| t.string :name t.timestamps end end end
中間テーブルのmember_position
class CreateMemberPositions < ActiveRecord::Migration[5.1] def change create_table :member_positions do |t| t.string :member_id t.string :position_id t.timestamps end end end
各モデルの設定
class Member < ApplicationRecord has_many :member_positions has_many :positions, through: :member_positions accepts_nested_attributes_for :member_positions, allow_destroy: true end class Position < ApplicationRecord has_many :member_positions has_many :members, through: :member_positions end class MemberPosition < ApplicationRecord belongs_to :member belongs_to :position end
members_controller
def new @member = Member.new end def create @member = Member.new(member_params) if @member.save flash[:success] = "新しいメンバーの追加が完了しました。" redirect_to members_path else render 'new' end end def index @members = Member.all end private def member_params params.require(:member).permit(:name, :introduction, position:[]) end
new.html.erb
<%= form_for(@member) do |f| %> <%= f.label :name, "氏名" %> <%= f.text_field :name %> <%= f.collection_check_boxes(:member_positions, Position.all, :id, :name ) do |t| %> <%= t.label { t.check_box + t.name } %> <% end %> <%= f.label :introduction, "選手紹介" %> <%= f.text_area :introduction, size: "77x5" %> <%= f.submit '新規登録', class: 'btn btn-primary button' %> <% end %>
position内のデータ
%w[ピッチャー キャッチャー ファースト セカンド サード ショート レフト センター ライト].each { |a| Position.create(name: a) }
index.html.erb
<% @members.each do |member| %> <%= member.name %> <%= member.position %> <%= member.introduction %> <% end %>
よろしくお願いいたします。
あなたの回答
tips
プレビュー