1

I want to build a table that I will show "Plans and Pricing", it will show features x plans.

Just an example... in the "basic" plan I have the "pageviews" feature with a limit to 20.000 pageviews, but for the "advanced" plan the "pageview" limit is 1.000.000.

I have a table "features" (id, name), a table "plans" (id, name), and a table "features_plans" (feature_id, plan_id, value)

How to build a form to save those data?

I have a form that I'm using checkboxes and it's working, but I have to do that filling the "value" field in the join table (features_plans).

models/feature.rb

class Feature < ActiveRecord::Base
    has_and_belongs_to_many :plans
end

models/plan.rb

class Plan < ActiveRecord::Base
    has_and_belongs_to_many :features
end

controllers/plans_controller.rb

def new
  @plan = Plan.new
  @features = Feature.where(product_id: params[:product_id])
end

def update
  respond_to do |format|
    if @plan.update(plan_params)
            ...
    end
  end
end

def plan_params
  params.require(:plan).permit(:product_id, :name, :monthly_payment, {:feature_ids => []})
end

views/plans/_form.html.erb

<% @features.each do |feature| %>
    <%= check_box_tag "plan[feature_ids][]", feature.id, @plan.features.include?(feature), id: "plan_feature_ids_#{feature.id}", for: "plan_feature_ids_#{feature.id}" %>
    <label for="<%= "plan_feature_ids_#{feature.id}" %>">
        <%= feature.name %>
    </label>
<% end %>

Should I take another way to do that? Should I use somenthing like ":through"?

maurymmarques
  • 329
  • 1
  • 3
  • 17
  • http://stackoverflow.com/questions/4924156/habtm-and-accepts-nested-attributes-for – Beartech Mar 06 '15 at 05:49
  • Read that link. I think that a Has Many :through could work better for you. It would allow you to use `accepts_nested_attributes_for` in your models. That way you can use a nested for. If I recall you have to use some hidden values when doing this with checkboxes. I'll try to find the reference for that. – Beartech Mar 06 '15 at 05:52
  • http://railscasts.com/episodes/17-habtm-checkboxes-revised?view=asciicast – Beartech Mar 06 '15 at 05:58
  • I'm using accepts_nested_attributes_for with "has_many" and "has_many" in both tables, but it isn't working. I'm not being able to build a form that will save data in the table "features_plans" – maurymmarques Mar 09 '15 at 18:26

0 Answers0