Skip to content

Instantly share code, notes, and snippets.

@dohoonk
Last active March 15, 2016 21:16
Show Gist options
  • Save dohoonk/6b6d01df518d97c7a050 to your computer and use it in GitHub Desktop.
Save dohoonk/6b6d01df518d97c7a050 to your computer and use it in GitHub Desktop.
dynamic _form/ cocoon gem

This line of code in campaign model will allow users to feed data about rewards accepts_nested_attributes_for :rewards, reject_if: :all_blank

_form.html.erb

<%= f.simple_fields_ for :rewards do |r| %> <%= r.input :title%> <%= r.input :amount%> <% end %>

campaigns controller

def new @campaign = Campaign.new 3.times { @campaign.rewards.build } end

def campaigns_params add {rewards_attributes: [:amount,:title,:id]}

show.html.erb

<% @campaign.rewards.each do |reward| %>

<%= reward.title %>

end

we should use validation for reward to prevent empty rewards

validates :amount, presence: true, numericality: {greater_than: 0}

REWARD_COUNT = 3

number_to_build = REWARD_COUNT - @campaign.rewards.size number_to_build.times { @campaign.rewards.build }

inorder to destroy

accepts_nested_attributes_for :rewards, reject_if: :all_blank, allow_destroy: true

<%=r.input :_destroy, as: :boolean %>

{rewards_attributes: [:amount,:title,:id,:_destroy]}


gem "cocoon"

In your application.js

after jquery add this code //= require cocoon

In your views - campaign folder create a new file _reward_field.html.erb

<%= simple_form_for @campaign do |f| %>
  <%= f.input :name, label: "Campaign Name", input_html: {class: "small-field"} %>
  <%= f.input :description %>
  <%= f.input :goal, as: :string %>
  <%= f.input :end_date %>
  <%# f.file_field :image  %>
  <%= f.input :image %>
  <div id="rewards">
    <%= f.simple_fields_for :rewards do |r| %>
      <%= render "reward_fields", f: r %>
    <% end %>
    <div class="links">
      <%= link_to_add_association "Add Reward", f, :rewards %>
    </div>
  </div>
  <%= f.submit class: "btn btn-primary" %>
<% end %>

<%= link_to_remove_association "remove reward", f %>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment