4

我有一个数据库,其中包含具有 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 %>
4

3 回答 3

0

在您的模型中,您具有“拥有并属于多个”关系,这意味着您的用户可以在 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

然后重构您的控制器,如下所示:

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

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

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

它现在有效吗?

于 2012-10-21T17:45:41.940 回答
0

可能这个答案已经过时了,但可能对最终在这里的谷歌用户有用:

当 Rails(4.2 for me) 更新 Has-And-Belongs-To-Many 关联时,它不会更改updated_at根记录的值。例子:

# This does not change @user.updated_at value 
@user.update_attributes(group_ids: [1, 2, 3])

每个 ActiveRecord 对象都有一个特殊cache_key的,通常使用updated_at缓存的值和无效来构建。因此,如果我们仅更改 HABT,它不会使缓存无效。

@user.touch此处可能的解决方案 -如果 HABTM 已更改,则手动调用。

于 2017-03-14T16:18:10.660 回答
0

如果有人因为创建或删除后数据不显示而来到这里,那么您需要执行以下操作以在这些操作之后更新缓存:

  # in your model file
  after_save    :expire_model_all_cache
  after_destroy :expire_model_all_cache

  def expire_model_all_cache
    Rails.cache.delete("your cache name")
  end
于 2020-04-03T10:28:37.900 回答