Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get selects to work with ActiveRecord associated records (belongs_to) #530

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Commits on Feb 4, 2016

  1. Get selects to work with ActiveRecord associated records (belongs_to)

    I have an ActiveRecord model that references another model, and I
    wanted to get Best In Place to create a select dropdown with a list of
    areas for the user.
    For my scenario, I have a Store that belongs to an Area.
    
    In my model I have:
    ```ruby
    class Store < ActiveRecord::Base
      belongs_to :area
    ```
    
    So in my view (I use am using haml):
    ```ruby
    = best_in_place @store, :area, :as => :select, :collection => @areas
    ```
    
    In routes.rb, make sure the stores can be updated:
    ```ruby
    resources :stores, only: [:index, :show, :update] do (etc)
    ```
    
    In stores_controller.rb:
    ```ruby
      def details
        @store = Store.find(params[:id])
        @areas = current_user.visible_areas
        #... etc
      end
    
      def update
        store = Store.find(params[:id])
        store.assign_attributes(update_params)
        store.save!
        respond_with_bip(store)
      end
    
      private
    
      def update_params
        params.require(:store).permit(:id, :area_id) # other fields in here
    of course!
      end
    ```
    
    Please note that the update_params need to be (say) :area_id rather
    than :area to work.
    
    Also I haven't managed to understand what respond_with_bip really does,
    so this might need more coding.
    peterwake committed Feb 4, 2016
    Configuration menu
    Copy the full SHA
    218f249 View commit details
    Browse the repository at this point in the history