Rails - 在清除缓存之前查看不使用新数据进行更新

时间:2012-09-29 17:51:31

标签: ruby-on-rails caching has-and-belongs-to-many

我有一个包含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 %>

3 个答案:

答案 0 :(得分:0)

在您的模型中,您拥有“拥有并且属于许多”关系,这意味着您的用户可以分为n个组,您的组包含n个用户。

@group.user_id

如果您在“groups”表中创建了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

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

您也可以在视图中重构很多内容,但这不是问题,我们会保留原样。

现在有用吗?

答案 1 :(得分:0)

可能这个答案已经过时,但对于最终会在这里结束的Google员工可能会有用:

当Rails(对我来说4.2)更新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,它不会使缓存无效。

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

答案 2 :(得分:0)

如果有人因为创建或删除后无法显示数据而来到这里,则需要执行以下操作来更新缓存:

public class C
{
    public dynamic getType()
    {
        if (some condition)
           return new B();
        if (some condition)
           return new D();
        return A();
    }   
}