これはおそらく本当にシンプルですが、私は数日間頭を悩ませてしまいましたが、それを理解できません!方向は非常に高く評価されるだろう!
私はcollective、group_membership &という3つのモデルを持っています。私は集合的なインデックス&ショーページのボタンを押すことによって、ユーザーが集団に加わることができるようにしたい。
group_membershipのコントローラが必要ですか?
collective_id & user_idの属性を隠しフィールドとして継承するフォームを使用することを考えましたが、結合ボタンをフォームの送信として使用しましたが、わかりませんでした。あなたが何かを知る必要があるなら、私に教えてください!
ここに私が持っているものの抽出があります。Rails 3つのモデルを使用してグループボタンに追加
モデル
class Collective < ActiveRecord::Base
has_many :group_memberships, dependent: :destroy
has_many :users, :through => :group_memberships
accepts_nested_attributes_for :group_memberships
end
class GroupMembership < ActiveRecord::Base
belongs_to :user
belongs_to :collective
validates_uniqueness_of :collective_id, :message => "can be only joined once", :scope => 'user_id'
end
class User < ActiveRecord::Base
validates :user_name, presence: true, length: { minimum: 4, maximum: 20 }
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :collectives, :through => :group_memberships
has_many :group_memberships
end
コレクティブコントローラ
class CollectivesController < ApplicationController
before_action :set_collective, only: [:show, :edit, :update, :destroy]
def index
@collectives = Collective.all
end
def show
@users_group = @collective.users
end
def new
@collective = Collective.new
end
def create
@collective = Collective.new(collective_params)
@collective.users << current_user
respond_to do |format|
if @collective.save
format.html { redirect_to @collective, notice: 'Collective was successfully created.' }
format.json { render :show, status: :created, location: @collective }
else
format.html { render :new }
format.json { render json: @collective.errors, status: :unprocessable_entity }
end
end
end
private
def set_collective
@collective = Collective.find(params[:id])
end
def collective_params
params.require(:collective).permit(:collectivename, :collectivedescription, :createdby)
end
インデックスエキス:
<tbody>
<% @collectives.each do |collective| %>
<tr>
<td><%= collective.collectivename %></td>
<td><%= collective.collectivedescription %></td>
<td><%= collective.createdby %></td>
<td><%= link_to 'Show', collective %></td>
<td><%= link_to 'Edit', edit_collective_path(collective) %></td>
<td><%= link_to 'Destroy', collective, method: :delete, data: { confirm: 'Are you sure?' } %></td>
**Here;s where I'd like to put the join button**
</tr>
<% end %>