In my Rails application, I have a campaign that belongs to a company. The company has many groups and one or more of those groups can be connected to the campaign trough a model called :general_connections
.
For this campaign I'm trying to show a list of groups (with checkboxes) for the associated company. By checking a box, a ':general_connection' should be created and by unchecking it, this specific ':general_connection' should be destroyed
.
Models:
class Company < ActiveRecord::Base
has_many :campaigns
has_many :groups
end
class Campaign < ActiveRecord::Base
belongs_to :company
has_many :general_connections
has_many :groups, through: :general_connections
end
class Group < ActiveRecord::Base
belongs_to :company
has_many :general_connections
has_many :campaigns, through: :general_connections
end
class GeneralConnection < ActiveRecord::Base
belongs_to :campaign
belongs_to :group
belongs_to :company
end
Controllers:
#campaign_controller.rb /show
def show
@campaign = Campaign.find(params[:id])
@company = Company.find(current_user.current_company)
@main_groups = @company.groups
@general_connections = @campaign.general_connections
@groups = @campaign.groups
end
#general_connection_controller.rb /connect_group_to_campaign
def connect_group_to_campaign
group = group.find(params[:group_id])
@campaign = Campaign.find(params[:id])
@campaign.general_connections.create(group: group)
redirect_to :back
end
#general_connection_controller.rb /disconnect_group_from_campaign
def disconnect_group_from_campaign
@general_connection = GeneralConnection.where("group_id = ? AND campaign_id = ?", params[:group_id], @campaign.id).first
group = @general_connection.oneliner
@general_connection.destroy
redirect_to :back
end
View with form_tag:
<h5>Groups for this campaign</h5>
<div class="row">
<% @main_groups.each do |group| %>
<%= form_tag connect_group_to_campaign_path do |f| %>
<%= hidden_field_tag 'campaign_id', @campaign.id %>
<%= f.check_box_tag group.id, group.id, true %>
<% end %>
<%= form_tag disconnect_group_from_campaign_path do |f| %>
<%= hidden_field_tag 'campaign_id', @campaign.id %>
<%= f.check_box_tag group.id, group.id, false %>
<% end %>
<% end %>
</div>
I believe that my attempt in the View is probably rubish, but I just wanted to first try it myself.
My questions are:
- Is this even possible?
- And if so, how can I compose this?
Aucun commentaire:
Enregistrer un commentaire