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

「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

これにより、現在のユーザーを含むグループが作成されます。あなたの方法では、あなたはあなたの変更を保存するのを忘れました。演算子=および<<はデータベースを更新しないためです。次に、少しリファクタリングしましたが、同じロジックです。

ビュー内の多くのことをリファクタリングすることもできますが、それは問題ではありません。そのままにしておきます。

今は動作しますか?

于 2012-10-21T17:45:41.940 に答える