rails many_to_many 关联问题
rails many_to_many association issue
无法访问由 current_user 创建的项目。
project_controller.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 %>
user
has_many project
和 project
has_many user
.
project.rb
has_many :users, through: :project_users
user.rb
has_many :project_users
项目_user.rb
belongs_to :user
belongs_to :project
与此相关 post-
检查一下你的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
无法访问由 current_user 创建的项目。
project_controller.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 %>
user
has_many project
和 project
has_many user
.
project.rb
has_many :users, through: :project_users
user.rb
has_many :project_users
项目_user.rb
belongs_to :user
belongs_to :project
与此相关 post-
检查一下你的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