ruby-on-rails - 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 %>
user
has_manyproject
和project
has_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
解决方案
检查您的 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
推荐阅读
- api - 嵌入谷歌搜索数据
- c# - 如何告诉 FluentValidation 不要检查请求中未包含的字段的子字段的规则?
- html - 为传入的句子保留 2 行文本
- javascript - 向自动生成的行元素添加功能
- spring - JdbcTemplate 中的多租户
- elasticsearch - 如果仅使用存在过滤器,则使用哪种 Elasticsearch 字符串数据类型?
- python - 如何将 Pandas 行的值排列到单独的数据框中?
- javascript - 运行 Jasmine 测试未找到课程
- php - 如何在 Windows 10 中添加 PHP 扩展?
- email - 是否有允许以编程方式创建地址的电子邮件服务提供商?