如何使用has_many添加现有记录:通过rails中的关联

时间:2017-02-17 15:23:40

标签: ruby-on-rails ruby-on-rails-4

我是铁杆新手。 我有一些小问题。我需要将项目添加到某个用户个人资料页面。例如:用户必须转到项目页面,并使用“添加到配置文件”按钮。 它应该将项目添加到用户配置文件。

但是当我使用“添加”

ActiveRecord::RecordNotFound (Couldn't find Profile with 'id'=):
  app/controllers/projects_controller.rb:15:in `add'

我有三种模式:

class ProjectList < ActiveRecord::Base

  belongs_to :profile
  belongs_to :project

end

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

  has_many :charts
end

class Profile < ActiveRecord::Base
  belongs_to :user

  has_many :project_lists
  has_many :projects, through: :project_lists

  has_attached_file :avatar, styles: { thumb: ["64x64#", :jpg, :png] }
  validates_attachment :avatar, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }


end

我的控制器:

class ProjectsController < ApplicationController

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


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

  def new
    @project = Project.new
  end

  def add
    @profile = Profile.find(params[:profile_id])
    @profile.projects << project

  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 add
  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, :profile_id)
  end

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

end

在我看来,使用助手:

<%= link_to 'Add', add_to_profile_path(@project), :class => 'btn btn-sm btn-info' %>

我的路线:

Rails.application.routes.draw do
  devise_for :users
  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  resources :profiles
  resources :charts

  get '/projects/add_project/:project_id', to: 'projects#add', as: 'add_to_profile'
  resources :projects


  root 'profiles#index'


end

在控制台中:

Started GET "/projects/add_project/2" for 127.0.0.1 at 2017-02-17 17:12:55 +0200
Processing by ProjectsController#add as HTML
  Parameters: {"project_id"=>"2"}
  Profile Load (0.1ms)  SELECT  "profiles".* FROM "profiles" WHERE "profiles"."id" = ? LIMIT 1  [["id", nil]]
Completed 404 Not Found in 4ms (ActiveRecord: 0.1ms)

ActiveRecord::RecordNotFound (Couldn't find Profile with 'id'=):
  app/controllers/projects_controller.rb:15:in `add'

我很感激任何帮助。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 首先,我将模型名称project_list更改为profiles_projects。

为我的模型创建ProfilesProjects控制器

class ProfilesProjectsController < ApplicationController

  def create
  @profiles_projects = _current_profile.profiles_projects.new(:project_id => params[:project_id])

  if @profiles_projects.save
    render status: 201, json: @profiles_projects
  end
end

  private

  def _current_profile
    @current_profile = current_user.profile
  end
end

它对我有用。现在我可以将项目添加到Profile。 也许它会帮助某人