gpt4 book ai didi

ruby-on-rails - Rails - 在清除缓存之前查看不更新新数据

转载 作者:行者123 更新时间:2023-12-03 17:55:00 24 4
gpt4 key购买 nike

我有一个数据库,其中包含具有 has_and_belongs_to_many 关系的用户和组。添加新组时,它会被创建,但在我清除缓存或使用隐身窗口登录之前,用户对该组的成员资格似乎不会传播。我知道它被正确保存了,它只是在清除缓存之前似乎没有加载。这只是最近才开始发生,我不知道为什么!任何帮助将不胜感激。

从模型:

class User < ActiveRecord::Base
has_many :services
has_many :recipes
has_and_belongs_to_many :groups
attr_accessible :recipes, :groups
end

class Group < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :recipes
attr_accessible :description, :title, :recipe, :picture, :featured, :user_id
end

创建组方法:
def create
@user = User.find(current_user.id)
@group = Group.new(params[:group])
@group.user_id = @user.id
@user.groups << @group

redirect_to group_path(@group)
end

显示用户的组成员资格 - 在清除缓存之前不会更新:
<% @user.groups.each do |group| %>
<% if group %>
<p class="group-title"><a href="<%= group_path(group) %>"><%= group.title %></p>
<% @latestpic = Recipe.where("group_id = ?", group).limit(1).order("created_at DESC") %>
<% if @latestpic.exists? %>
<% @latestpic.each do |pic| %>
<%= image_tag(pic.picture.url(:medium)) %>
<% end %></a>
<% else %>
<%= image_tag "http://placehold.it/300x300" %>
<% end %>
<br></br>

<% end %>
<% end %>

最佳答案

在你的模型中,你有一个“has and属于 many”的关系,这意味着你的用户可以在 n 个组中,你的组包含 n 个用户。

@group.user_id

如果您在“组”表中创建了 user_id 列,则可以删除它,因为一个组包含 n 个用户。您必须在用户和组之间使用一个表,如下所示:
create_table :group_users, :id => false do |t|
t.references :group, :null => false
t.references :user, :null => false
end

然后像我下面那样重构你的 Controller :
def create
@group = current_user.groups.build(params[:group])

if @group.save
redirect_to @group, notice: 'Group was successfully created.'
else
render action: "new"
end
end

这将创建一个包含您当前用户的组。在您的方法中,您忘记保存修改。因为运算符 = 和 << 不会更新数据库。然后我重构了一点,但它是相同的逻辑。

您还可以在您的 View 中重构很多东西,但这不是问题,我们将保持原样。

现在有效吗?

关于ruby-on-rails - Rails - 在清除缓存之前查看不更新新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12655045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com