0

Есть три модели

class Profile < ActiveRecord::Base
  belongs_to :user

  has_many :project_lists
  has_many :projects, through: :project_lists

end

class Project < ActiveRecord::Base
  has_many :project_lists
  has_many :profiles, through: :project_lists

  has_many :charts
end

class ProjectList < ActiveRecord::Base

  belongs_to :profile
  belongs_to :project

end

Суть проблемы, нужно добавить project на страницу profile юзера. Например: пользователь заходит на страницу проектов, и кнопкой add добавляет проект который понравился себе на страницу.

Связь работает, через консоль добавляю удаляю проекты.

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

class ProjectsController < ApplicationController

  before_action :find_project, only: [:show, :edit, :update, :destroy, :add]


  def index
    @projects = Project.all.paginate(page: params[:page], per_page: 5)
  end

  def new
    @project = Project.new
  end

  def edit
  end

  def update
    if @project.update(project_params)
      redirect_to projects_path
    else
      render 'edit'
    end
  end

  def create
    @project = Project.new(project_params)
    #@project.profiles.build(params[:profile_id])

    if @project.save
      flash[:create] = 'Project created'
      redirect_to projects_path
    else
      render 'new'
    end
  end

  def show
  end

  def destroy
    @project.destroy
    flash[:destroy] = 'Delete project'
    redirect_to projects_path
  end

  private

  def project_params
    params.require(:project).permit(:project_name, :project_id, :description)
  end

  def find_project
    @project = Project.find(params[:id])
  end

end

class ProfilesController < ApplicationController

  #before_action :authenticate_user!, except: [:index]
  before_action :find_profile, only: [ :show, :edit, :update, :destroy]

  def index
    @profiles = Profile.all.paginate(page: params[:page], per_page: 5)

  end

  def show
  end

  def new
    @profile = Profile.new
  end

  def edit
  end

  def create
  end

  def update
    respond_to do |format|
      if @profile.update(profile_params)
        format.json { head :no_content }
        format.js
        format.html do
          redirect_to '/'
        end
      else
        format.json { render json: @profile.errors.full_messages,
                             status: :unprocessable_entity }
      end

    end
  end

  def destroy
    @profile.destroy

    respond_to do |format|
      format.js
      format.html { redirect_to profiles_url }
      format.json { head :no_content }
    end
  end

  private

  def profile_params
    params.require(:profile).permit(:name, :birthday, :biography, :user_id, :avatar)
  end

  def find_profile
    @profile = Profile.find(params[:id])
  end

end

Пробовал так:

def add
    @profile = Profile.find(profile_params)
    @profile.projects << Project.find(params[:project_id])
  end

и в роутах

get '/projects/:project_id', to: 'profiles#add', as: 'add'

Получается так:

Started GET "/projects/3" for 127.0.0.1 at 2017-02-09 12:23:17 +0200
  ActiveRecord::SchemaMigration Load (0.2ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by ProjectsController#show as JS
  Parameters: {"id"=>"3"}
  Project Load (0.2ms)  SELECT  "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT 1  [["id", 3]]
  Rendered projects/show.html.erb within layouts/application (4.0ms)
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 19]]
Completed 200 OK in 321ms (Views: 294.7ms | ActiveRecord: 1.0ms)
7
  • И какие решения вы уже пробовали? Я в вопросе не вижу ни одного.
    – user181100
    8 фев 2017 в 20:40
  • @D-side Пробовал зделать так 'def add profile = Profile.find(profile_params) profile.projects << Project.find(params[:project_id]) end'
    – Jhonson
    9 фев 2017 в 8:21
  • И-и-и что произошло?
    – user181100
    9 фев 2017 в 9:00
  • @D-side обновил пост добавил логи)
    – Jhonson
    9 фев 2017 в 10:25
  • Это логи от GET "/projects/3" aka projects#show id=3.
    – user181100
    9 фев 2017 в 11:03

0

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Посмотрите другие вопросы с метками или задайте свой вопрос.