Arhn - архитектура программирования

вкладки навигации, используемые двумя моделями и контроллерами с has_many и blongs_to

У меня есть две модели с has_many и own_to с вложенными ресурсами и независимыми представлениями. Я создал навигационные вкладки, которые я хочу отображать на обоих контроллерах. Навигационные вкладки работают для просмотра поездки, но не работают в указателе местоположений. Мне нужно передать локальный .. что-то, чтобы заработало, и я не знаю, как это сделать. Это ошибка, которую я получаю. Маршрут не соответствует {:action=>"show", :controller=>"trips", :trip_id=>"13"} отсутствуют необходимые ключи: [:id] для этой строки: a.slow href=send("trip_url" ) Путешествие

Модель поездки

class Trip < ApplicationRecord


  has_many :user_trips
  has_many :users, through: :user_trips, dependent: :destroy
  belongs_to :creator, class_name: "User"
  # has_many :locations, dependent: :destroy
  # belongs_to :location, optional: true, inverse_of: :locations
  has_many :locations

  accepts_nested_attributes_for :locations,  :reject_if => :all_blank, :allow_destroy => true

end

модель местоположения

class Location < ApplicationRecord
  # has_many :trips, inverse_of: :trips
  belongs_to :trip, optional: true
  # accepts_nested_attributes_for :trips,  :reject_if => :all_blank, :allow_destroy => true
end

Маршруты

Rails.application.routes.draw do

  resources :locations

  resources :trips do
    resources :locations
  end
end

путевой контроллер

class TripsController < ApplicationController
  before_action :set_trip, only: [:show, :edit, :update, :destroy]

  # GET /trips
  # GET /trips.json
  def index
    @trips = Trip.all
  end

  # GET /trips/1
  # GET /trips/1.json
  def show
  end

  # GET /trips/new
  def new
    @user = current_user
    @trip = current_user.trips.build
  end

  # GET /trips/1/edit
  def edit
    @user = current_user
  end

  # POST /trips
  # POST /trips.json
  def create
    @user = current_user
    @trip = current_user.trips.build(trip_params)

    respond_to do |format|
      if @trip.save
        # @trip.users << @user
        format.html { redirect_to @trip, notice: 'Trip was successfully created.' }
        format.json { render :show, status: :created, location: @trip }
      else
        format.html { render :new }
        format.json { render json: @trip.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /trips/1
  # PATCH/PUT /trips/1.json
  def update
    respond_to do |format|
      if @trip.update(trip_params)
        format.html { redirect_to @trip, notice: 'Trip was successfully updated.' }
        format.json { render :show, status: :ok, location: @trip }
      else
        format.html { render :edit }
        format.json { render json: @trip.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /trips/1
  # DELETE /trips/1.json
  def destroy
    @trip.destroy
    respond_to do |format|
      format.html { redirect_to trips_url, notice: 'Trip was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def trip_params
      params.require(:trip).permit(:name, :description, :creator_id, :location_id, user_ids: [])
    end
end

контроллер местоположения

class LocationsController < ApplicationController
  # before_action :set_location, only: [:show, :edit, :update, :destroy]
  # before_action :set_trip

  # GET /locations
  # GET /locations.json
  def index
    trip = Trip.find(params[:trip_id])
    @locations = trip.locations
    # @locations = trip.locations
  end

  # GET /locations/1
  # GET /locations/1.json
  def show
    @trip = Trip.find(params[:trip_id])
    trip = Trip.find(params[:trip_id])
    @location = trip.locations.find(params[:id])
  end

  # GET /locations/new
  def new
    trip = Trip.find(params[:trip_id])
    @location = trip.locations.build
  end

  # GET /locations/1/edit
  def edit
    trip = Trip.find(params[:trip_id])
    #2nd you retrieve the comment thanks to params[:id]

    @location = trip.locations.find(params[:id])

  end

  # POST /locations
  # POST /locations.json
  def create
    # @location = Location.new(location_params)
    trip = Trip.find(params[:trip_id])
    @location = trip.locations.create(params[:location_params])
    respond_to do |format|
      if @location.save
        format.html { redirect_to trip_locations_url, notice: 'Location was successfully created.' }
        format.json { render :show, status: :created, location: @location }
      else
        format.html { render :new }
        format.json { render json: @location.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /locations/1
  # PATCH/PUT /locations/1.json
  def update
    trip = Trip.find(params[:trip_id])
    @location = trip.locations.find(params[:id])
    respond_to do |format|
      if @location.update(location_params)
        format.html { redirect_to trip_locations_url, notice: 'Location was successfully updated.' }
        format.json { render :show, status: :ok, location: @location }
      else
        format.html { render :edit }
        format.json { render json: @location.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /locations/1
  # DELETE /locations/1.json
  def destroy
    trip = Trip.find(params[:trip_id])
    @location = trip.locations.find(params[:id])
    @location.destroy
    respond_to do |format|
      format.html { redirect_to trip_locations_url, notice: 'Location was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_trip
      trip = Trip.find(params[:trip_id])
    end

    # def set_location
    #   trip = Trip.find(params[:trip_id])
    #   @location = trip.locations.find(params[:id])
    #   # @location = Location.find(params[:id])
    # end
    # post = Post.find(params[:post_id])
    # #2nd you retrieve the comment thanks to params[:id]
    #
    # @comment = post.comments.find(params[:id])
    #

    # Never trust parameters from the scary internet, only allow the white list through.
    def location_params
      params.require(:location).permit(:name, :image, :street_address_1, :street_address_2, :city, :state, :zip_code, :country_code, :trip_id)
    end
end

Вкладка навигации

view/nav/_tabs.html.slim
    - if can?(:read, @trip)

  - controller = params[:controller].singularize
  ul.nav.nav-tabs#tabs
      li class=('active' if params[:action] == 'show')
        = link_to 'Trip', trip_path(@trip)

      li class=('active' if params[:action] == 'index')
        = link_to 'Location', trip_locations_url(@trip)

      li class=('active' if params[:action] == 'inex')
        = link_to 'Members'

      li class=('active' if params[:action] == 'index')
        = link_to 'Events'

      li class=('active' if params[:action] == 'index')
        = link_to 'Status'

просмотр указателя местоположения

header.intro-location
  .intro-body
    .container
      .row
        .col-md-18
          h1.brand-heading
            = render 'nav/tabs'
            h1.space-above Locations

            -if can?(:create, @locations)
            = link_to "Add New Location", new_trip_location_path, class: 'btn btn-xs btn-primary space-right'

            table.table.table-striped-location.table-hover-location.space-above
              thead
                tr
                  th Name
                  th Image
                  th Street address 1
                  th Street address 2
                  th City
                  th State
                  th Zip code
                  th Country code
                  th
                  th
                  th

              tbody
                - @locations.each do |location|
                  tr
                    td = location.name
                    td = location.image
                    td = location.street_address_1
                    td = location.street_address_2
                    td = location.city
                    td = location.state
                    td = location.zip_code
                    td = location.country_code
                    td = link_to 'Show', trip_location_url(location.trip, location), class: 'btn btn-xs btn-success space-right'
                    td = link_to 'Edit', edit_trip_location_url(location.trip, location), class: 'btn btn-xs btn-primary space-right'
                    td = link_to 'Destroy', [location.trip, location], data: { confirm: 'Are you sure?' }, method: :delete, class: 'btn btn-xs btn-danger space-right'

просмотр трип-шоу

p#notice = notice
header.intro-location
  .intro-body
    .container
      .row
        .col-md-14
          h3.brand-heading
            = render 'nav/tabs'
        .col-md-6.h4
          table.table.table-striped-location.table-hover-location.space-above
            thead
              tr
                th Name:
                td.show = @trip.name
              tr
                th Description:
                td.show = @trip.description


      => link_to 'Edit', edit_trip_path(@trip), class: 'btn btn-xs btn-primary space-right'
      '|
      =< link_to 'Back', trips_path, class: 'btn btn-xs btn-info space-right'
28.04.2019

Ответы:


1

Обновлена ​​навигационная панель

- if can?(:read, @trip)

  - controller = params[:controller].singularize
  ul.nav.nav-tabs#tabs
      li class=('active' if params[:action] == 'show')
        = link_to 'Trip', trip_path(@trip)

      li class=('active' if params[:action] == 'index')
        = link_to 'Location', trip_locations_url(@trip)

      li class=('active' if params[:action] == 'inex')
        = link_to 'Members'

      li class=('active' if params[:action] == 'index')
        = link_to 'Events'

      li class=('active' if params[:action] == 'index')
        = link_to 'Status'

Добавлен @trip в класс контроллера местоположения/индекса LocationsController ‹ ApplicationController

def index
    @trip = Trip.find(params[:trip_id])
    trip = Trip.find(params[:trip_id])
    @locations = trip.locations
    # @locations = trip.locations
  end
09.05.2019
Новые материалы

Коллекции публикаций по глубокому обучению
Последние пару месяцев я создавал коллекции последних академических публикаций по различным подполям глубокого обучения в моем блоге https://amundtveit.com - эта публикация дает обзор 25..

Представляем: Pepita
Фреймворк JavaScript с открытым исходным кодом Я знаю, что недостатка в фреймворках JavaScript нет. Но я просто не мог остановиться. Я хотел написать что-то сам, со своими собственными..

Советы по коду Laravel #2
1-) Найти // You can specify the columns you need // in when you use the find method on a model User::find(‘id’, [‘email’,’name’]); // You can increment or decrement // a field in..

Работа с временными рядами спутниковых изображений, часть 3 (аналитика данных)
Анализ временных рядов спутниковых изображений для данных наблюдений за большой Землей (arXiv) Автор: Рольф Симоэс , Жильберто Камара , Жильберто Кейрос , Фелипе Соуза , Педро Р. Андраде ,..

3 способа решить квадратное уравнение (3-й мой любимый) -
1. Методом факторизации — 2. Используя квадратичную формулу — 3. Заполнив квадрат — Давайте поймем это, решив это простое уравнение: Мы пытаемся сделать LHS,..

Создание VR-миров с A-Frame
Виртуальная реальность (и дополненная реальность) стали главными модными терминами в образовательных технологиях. С недорогими VR-гарнитурами, такими как Google Cardboard , и использованием..

Демистификация рекурсии
КОДЕКС Демистификация рекурсии Упрощенная концепция ошеломляющей О чем весь этот шум? Рекурсия, кажется, единственная тема, от которой у каждого начинающего студента-информатика..