首页 > 解决方案 > rails many_to_many 关联问题

问题描述

无法访问 current_user 创建的项目。

项目控制器.rb

def index
  @projects = current_user.projects.all
end

  def create
    @project = current_user.projects.build(project_params)

    respond_to do |format|
      if @project.save
        #ProjectMailer.activity_status(@project).deliver

        format.html { redirect_to projects_url, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

index.html.erb

      <% @projects.each do |project| %>
        <tr>
          <td><%= project.project_name %></td>
<tr>
<% end %>

userhas_manyproject
projecthas_many user

项目.rb

has_many :users, through: :project_users

用户.rb

  has_many :project_users

项目用户.rb

  belongs_to :user
  belongs_to :project

关联到这个 post -issue in has_and_belongs_to_many 关联在 rails

标签: ruby-on-railsruby-on-rails-5

解决方案


检查您的 user.rb 模型,我想应该是

has_many :project_users
has_many :projects,  through: :project_users

在您的项目模型中:

has_many :project_users
has_many :users, through: :project_users

请参阅此处的文档https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association


推荐阅读