簡體   English   中英

麻煩“ has_many通過:”關系

[英]Trouble with `has_many through:` Relationship

我正在設置用戶,網站和標簽模型,但是不確定正確的關聯嗎?

這是一個CRUD應用程序,我要允許用戶創建“網站”(本質上是書簽),並能夠向該網站添加“標簽”,以便可以過濾網站。

我有三個表: UserWebsiteTag

我想,用戶有很多網站,網站有很多標簽,標簽屬於網站,並且用戶通過網站有很多標簽。

我已經設置了以下模型:

class User < ActiveRecord::Base
  has_many :websites
  has_many :tags, through: :websites
end

class Website < ActiveRecord::Base
  belongs_to :user
  has_many :tags
end

class Tag < ActiveRecord::Base
  belongs_to :website
end

我通過發帖請求保存標簽:

post '/websites' do
  if logged_in?
    if params[:content] == ""
      redirect to "/websites/new"
    else
      @website = current_user.websites.build(content: params[:content])
      binding.pry
      @tag = current_user.tags.build(content: params[:dropdown])
      if @website.save && @tag.save
        redirect to "/websites/#{@website.id}"
      else
        redirect to "/websites/new"
      end
    end
  else
    redirect to '/login'
  end
end

當我在binding.pry檢查params時,它給了我預期的效果:

{content=>"tryingtoaddtag.com", "dropdown"=>"Clothing"}

我的期望是能夠保存一個用戶實例,然后使用@user.tags顯示與該用戶的網站關聯的所有標簽。 我不太清楚自己在搞砸。 謝謝。

閱讀這篇文章 ,然后試試這個:

class Tag < ActiveRecord::Base
  belongs_to :website
  delegate :user, :to => :website, :allow_nil => true
end

如果這不起作用。 User模型中使用范圍

def tags
 Tags.where(website_id: self.websites.pluck(:id))
end

考慮一個網站has_many:tags

class User < ActiveRecord::Base
  has_many :websites

  def user_tags
    Tag.joins(:website).where(websites: {user_id:  self.id})
  end

end

class Website < ActiveRecord::Base
  belongs_to :user
  has_many :tags
end

class Tag < ActiveRecord::Base
  belongs_to :website
end

查詢-

user = User.first
user.user_tags

嘗試以下,

class User < ActiveRecord::Base
  has_many :websites 
end

class Website < ActiveRecord::Base
  belongs_to :user
  has_many :tags
end

class Tag < ActiveRecord::Base
  belongs_to :website
  scope :user_tags, ->(user) { joins(:website).where(websites: {user_id:  user}) }
end

查詢看起來像(對於@user對象)

Tag.user_tags(@user)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM