2012-09-29 30 views
3

我有一個包含具有has_and_belongs_to_many關係的用戶和組的數據庫。添加新組時,會創建該組,但用戶對組的成員身份似乎不會傳播,直到我清除緩存或使用隱身窗口登錄。我知道它正在正確保存,它只是似乎沒有加載,直到緩存被清除。這只是最近纔開始發生的,我無法弄清楚爲什麼!任何幫助將不勝感激。Rails - 在清除緩存之前,不會使用新數據更新

從型號:

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 %> 
+0

@AdamEberlin - 我是一個鐵軌noob。我將如何檢查? – Kim

+0

您是否在使用RAILS獨立服務器或其他服務來爲您的RAILS應用程序提供服務?什麼操作系統? –

+0

@AdamEberlin - 我正在使用瘦Web服務器(v1.4.1代號Chromeo)。我在Mac OS上。這個問題發生在本地,並在Heroku上託管。 – Kim

回答

0

在你的模型中你有一個「有和屬於很多」的關係,這意味着你的用戶可以在n gro並且您的組包含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 

這將創建一個組在它當前的用戶。在你的方法中,你忘了保存你的修改。因爲operator =和< <不會更新數據庫。然後我重構一點,但它是相同的邏輯。

你也可以重構你視圖中的很多東西,但這不是問題,我們會保持原樣。

現在有效嗎?

0

可能這個答案已經過時,但可能是誰結束,在這裏的Google有用:

當鐵軌(4.2我)更新完成 - 和 - 屬於-to-many關聯,它不會改變根記錄的值爲updated_at。例如:

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

每個ActiveRecord對象具有通常使用的updated_at值和緩存無效建有專門的cache_key是基於這一點。所以,如果我們只更改HABT,它不會使緩存失效。

可能的解決方法 - 如果HABTM已更改,請手動呼叫@user.touch

相關問題