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

标签 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 %>

最佳答案

在你的模型中,你有一个“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/

相关文章:

laravel - Laravel 中与数据透视表的多态关系?

mysql - Eloquent belongsToMany 和三表(包括 Pivot)

ruby-on-rails - ruby rails : Server error with while trying to upload a file using attachment_fu: (can't convert nil into Integer)

ruby-on-rails - rails : rubocop disable Class has too many lines error

caching - Cache 和 Translation LookAside Buffer [TLB] 的区别

wordpress - Varnish 未启动语法错误

ruby-on-rails - 当我尝试使用 HABTM check_box_tag 保存时,为什么会出现“未经允许的参数”错误?

ruby-on-rails - 编写具有重复值的 Ruby Hash 而不重复值

ruby-on-rails - 有人可以帮助我理解node.js 以及如何以及为什么我可以将它与rails 这样的框架一起使用吗?

c# - ServiceStack ApiKeyAuthProvider 在每个请求上触发 6 个选择语句