1

In rails 4 application With has_many :through relations

city.rb

has_many :business_type_cities
has_many :business_types, :through => :business_type_cities

business_type.rb

has_many :business_type_cities 
has_many :cities, :through => :business_type_cities

businesstypecity.rb

belongs_to :buness_types
belongs_to :cities

business_types_controller.rb

def create
  if business_type.save
    BusinessTypeCity.create :business_type_id => business_type.id,        :city_id => params[:cities]
    flash[:notice] = 'Business Type Created Successfully!'
    redirect_to admin_business_types_path
  else
    flash[:error] = business_type.errors.full_messages.join(', ')
  end
end

but here city_id is array and I want to store business_type_id and city_id in one row, other city_id will store in different row with same business_type_id.

Response I get is following:

"business_type"=>{"name"=>"test", "review_type"=>"review_with_rating"}, "cities"=>["293", "1091", "1200"], "commit"=>"Create Business Type"

Thanks

1
  • Simple, I need to iterate params[:cities] with each do. Although if you have a better answer then interested in that. Thanks any way for your time. Commented Aug 23, 2016 at 7:56

1 Answer 1

1

The usual approach would be what you suggested in the comment. Here's what I usually do

existing_city_ids = business_type.city_ids
business_type.city_ids = existing_city_ids | params[:cities].map(&:to_i)

First getting all the existing city ids for the current business type. Then combine with the new ones, using || to avoid duplicates, and mapping params[:cities] to int to match with business_type.city_ids (returns an array of int)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.