2016-11-10 4 views
0

Я пытаюсь узнать, как использовать модели с именами в моем приложении Rails 5, чтобы лучше организовать мой контент.Rails 5 - как установить маршруты для моделей с именами

У меня есть адресная модель. Это полиморфно. У каждого из настроек и организации есть много адресов. Параметры - это модель, которая именуется под пользователем.

Ассоциации являются

Пользователь

has_one :setting, dependent: :destroy 

Установка

belongs_to :user 

    has_many :addresses, as: :addressable#, class_name: Address 
    accepts_nested_attributes_for :addresses, reject_if: :all_blank, allow_destroy: true 

Организация

has_many :addresses, as: :addressable#, class_name: Address 
    accepts_nested_attributes_for :addresses, reject_if: :all_blank, allow_destroy: true 

Адрес

belongs_to :addressable, :polymorphic => true, optional: true 

Маршруты - организация

resources :organisations do 
    namespace :contacts do 
     resources :addresses 
     resources :phones 
    end 
    end 

Маршруты - установка

resources :users, shallow: true do 
    scope module: :users do 
     resources :identities 
     resources :settings do 
     namespace :contacts do 
      resources :addresses 
      resources :phones 
     end 
     end 
    end 
    end 

Организация Форма

<%= f.simple_fields_for :addresses do |f| %> 
     <%= f.error_notification %> 
     <%= render 'contacts/addresses/address_fields', f: f %> 

    <% end %> 
     <%= link_to_add_association 'Add another address', f, :addresses, partial: 'contacts/addresses/address_fields' %> 

пользователь/установка формы

<%= simple_form_for [@user, @setting] do |f| %> 
    <%= f.error_notification %> 

    <%= simple_fields_for :addresses do |f| %> 
      <%= f.error_notification %> 
       <%= render 'contacts/addresses/address_fields', f: f %> 
      <% end %>  
      <%= link_to_add_association 'Manage address', f, :addresses, partial: 'contacts/addresses/address_fields' %>  

    </div> 
<% end %> 

Все, что касается моей адресной функции, отлично подходит для организации, но у меня есть проблема с тем, чтобы она работала для моих настроек.

У меня есть проблема, когда я пытаюсь использовать пользователь/настройкой формы для добавления адреса в том, что я получаю ошибку, которая говорит:

ActionController::RoutingError at /contacts/addresses/1/edit 
uninitialized constant Users::Contacts 

Существует не прямая связь между пользователем и контактами. Контакты - это имя папки с именами, которую я использую для хранения адресов и контроллера.

Может ли кто-нибудь увидеть, что мне нужно сделать, чтобы иметь возможность получить доступ к функциональности адресной формы из моей формы пользовательских настроек?

Когда я набираю маршруты для настройки, я могу видеть формат пути, чтобы получить адрес настроек, но я не могу понять, как его использовать.

rake routes | grep setting 
      setting_contacts_addresses GET  /settings/:setting_id/contacts/addresses(.:format)      users/contacts/addresses#index 
             POST  /settings/:setting_id/contacts/addresses(.:format)      users/contacts/addresses#create 
     new_setting_contacts_address GET  /settings/:setting_id/contacts/addresses/new(.:format)     users/contacts/addresses#new 

НАСТРОЙКИ CONTROLLER

class Users::SettingsController < ApplicationController 
    before_action :set_setting, only: [:show, :edit, :update, :destroy] 
    before_action :authenticate_user! 
    after_action :verify_authorized 

    def index 
    @settings = Setting.all 
    authorize @settings 

    end 

    def show 
    # authorize @setting 

    @addresses = @setting.addresses.all 

    @phones = @setting.phones 

    end 


    def new 
    @setting = Setting.new 
    @setting.addresses_build 
    @setting.phones_build 
    authorize @setting 

    end 

    def edit 
    @setting.addresses_build unless @setting.addresses 
    @setting.phones_build unless @setting.phones 

    end 

    def create 
    @setting = Setting.new(setting_params) 
    authorize @setting 

    respond_to do |format| 
     if @setting.save 
     format.html { redirect_to @setting } 
     format.json { render :show, status: :created, location: @setting } 
     else 
     format.html { render :new } 
     format.json { render json: @setting.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    def update 
    respond_to do |format| 
     if @setting.update(setting_params) 
     format.html { redirect_to @setting } 
     format.json { render :show, status: :ok, location: @setting } 
     else 
     format.html { render :edit } 
     format.json { render json: @setting.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    def destroy 
    @setting.destroy 
    respond_to do |format| 
     format.html { redirect_to settings_url } 
     format.json { head :no_content } 
    end 
    end 


    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_setting 
     @setting = Setting.find(params[:id]) 
     authorize @setting 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def setting_params 
     params.require(:setting).permit(:newsletter, 
     addresses_attributes: [:id, :description, :unit, :building, :street_number, :street, :city, :region, :zip, :country, :time_zone, :latitude, :longitude, :_destroy], 
     phones_attributes: [:phone_number, :country, :phone_type], 

     ) 
    end 

end 

ОРГАНИЗАЦИИ УПРАВЛЕНИЯ

class OrganisationsController < ApplicationController 
    before_action :set_organisation, only: [:show, :edit, :update, :destroy] 

    def index 
    @organisations = Organisation.all 
    authorize @organisations 
    end 

    def show 
    @addresses = @organisation.addresses.all 

    # @hash = Gmaps4rails.build_markers(@addresses) do |address, marker| 
    #  marker.lat address.latitude 
    #  marker.lng address.longitude 
    #  marker.infowindow address.full_address 
    # end 
    @bips = @organisation.bips 
    @proposals = @organisation.proposals#.in_state(:publish_openly)  
    end 

    def new 
    @organisation = Organisation.new 
    @organisation.addresses#_build 
    end 

    def edit 
    @organisation.addresses_build unless @organisation.addresses 
    end 

    def create 
    @organisation = Organisation.new(organisation_params) 

    respond_to do |format| 
     if @organisation.save 
     format.html { redirect_to @organisation, notice: 'Organisation was successfully created.' } 
     format.json { render :show, status: :created, location: @organisation } 
     else 
     format.html { render :new } 
     format.json { render json: @organisation.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    def update 
    respond_to do |format| 
     if @organisation.update(organisation_params) 
     format.html { redirect_to @organisation, notice: 'Organisation was successfully updated.' } 
     format.json { render :show, status: :ok, location: @organisation } 
     else 
     format.html { render :edit } 
     format.json { render json: @organisation.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    def destroy 
    @organisation.destroy 
    respond_to do |format| 
     format.html { redirect_to organisations_url, notice: 'Organisation was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 




private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_organisation 
     @organisation = Organisation.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def organisation_params 
     params.fetch(:organisation, {}).permit(:title, :comment, 
     addresses_attributes: [:id, :description, :unit, :building, :street_number, :street, :city, :region, :zip, :country, :time_zone, :latitude, :longitude, :_destroy], 
     phones_attributes:  [:id, :phone_number, :country, :phone_type, :_destroy] 
     ) 
    end 


end 

ответ

0

Я не совсем понимаю, что вы пытаетесь достичь. Эти коды ниже позволяют вам создать новый параметр для пользователя. Вы можете добавить дополнительные адреса в этот параметр. Если вы хотите изменить имя адреса, вам нужно перейти на страницу редактирования настройки, к которой принадлежит этот адрес.

routes.rb

resources :users, shallow: true do 
    scope module: :users do 
    resources :settings 
    end 
end 

пользователей/settings_controller.rb

class Users::SettingsController < ApplicationController 
    before_action :prepare_user, only: [:index, :new, :create] 
    before_action :prepare_setting, only: [:show, :edit, :update] 

    def new 
    @setting = Setting.new 
    end 

    def create 
    @setting = @user.build_setting(setting_params) 
    if @setting.save 
     redirect_to @setting 
    else 
     render 'new' 
    end 
    end 

    def show 
    end 

    def edit 
    end 

    def update 
    if @setting.update(setting_params) 
     redirect_to @setting 
    else 
     render 'edit' 
    end 
    end 

    private 

    def prepare_user 
    @user = User.find(params[:user_id]) 
    end 

    def prepare_setting 
    @setting = Setting.find(params[:id]) 
    end 

    def setting_params 
    params.require(:setting).permit(:name, addresses_attributes: [:name, :id]) 
    end 
end 

пользователей/Настройки/new.html.erb

<h1>New Setting</h1> 
<%= render 'form' %> 

пользователей/настройки/_form.html. erb

<%= simple_form_for [@user, @setting] do |f| %> 
    <%= f.input :name %> 
    <div> 
    <%= f.simple_fields_for :addresses do |f| %> 
     <%= f.error_notification %> 
     <%= render 'contacts/addresses/address_fields', f: f %> 
    <% end %> 
    <%= link_to_add_association 'Add another address', f, :addresses, partial: 'contacts/addresses/address_fields' %> 
    </div> 
    <%= f.submit %> 
<% end %> 

контакты/адреса/address_fields.html.erb

<%= f.input :name, label: 'Address name' %> 
<%= f.input :id, as: :hidden %> 
+0

Что вы думаете должны идти внутри []? Означает ли это, что мне также необходимо указать определенные действия для объявления настроек внутри области? – Mel

+0

Пустой [] будет в порядке. Все маршруты для настроек определены в первых 'resoures: settings' внутри' scope module:: users'. Второй 'resources: settings' предназначен только для определения вложенных ресурсов для' адресов' и ​​'phone', которые не находятся под пространством имен' users' – phamhoaivu

+0

Я пробовал это, но я все равно получаю ту же ошибку: неинициализированная константа Пользователи :: Контакты – Mel