Trouble with `has_many through:` Relationship





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I'm setting up a User, Website, and Tag model, but am unsure of the correct associations?



This is a CRUD app in which I want to allow the User to create a 'website' (a bookmark essentially) and be able to add a 'tag' to that website so that websites can be filtered.



I have three tables: User, Website, Tag



I want, User to have many websites, website has many tags, tags belong to website, and a user has many tags through websites.



I already have the following models set up:



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


I am saving the tag via a post request:



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


When I check params at the binding.pry it gives me as expected:



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


My expectation is to be able to save an instance of a user and then use @user.tags to show all tags associated with that user's websites. I can't quite figure out where I'm messing up. Thank you.










share|improve this question




















  • 3





    what do you get from @user.tags?

    – G.B
    Jan 3 at 12:22











  • So I created a website with a tag of Travel and when I drop into pry and type Tag.last it gives me that as expected. But User.all[0].tags is giving me an empty array. I double checked that User.all[0] gives me the correct user that is creating the website/tag

    – Austin Burke
    Jan 3 at 12:34











  • Can you try User.first.tags.to_sql and see if it correctly joining the tables in sql?

    – punitcse
    Jan 3 at 12:38











  • So this is what it gave back: "SELECT "tags".* FROM "tags" INNER JOIN "websites" ON "tags"."website_id" = "websites"."id" WHERE " websites"."user_id" = 1"

    – Austin Burke
    Jan 3 at 12:51













  • Can you try current_user.tags.build(content: params[:dropdown], website: @website)? if that not work you can first save @website and then pass website id while building.

    – punitcse
    Jan 3 at 13:04


















0















I'm setting up a User, Website, and Tag model, but am unsure of the correct associations?



This is a CRUD app in which I want to allow the User to create a 'website' (a bookmark essentially) and be able to add a 'tag' to that website so that websites can be filtered.



I have three tables: User, Website, Tag



I want, User to have many websites, website has many tags, tags belong to website, and a user has many tags through websites.



I already have the following models set up:



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


I am saving the tag via a post request:



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


When I check params at the binding.pry it gives me as expected:



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


My expectation is to be able to save an instance of a user and then use @user.tags to show all tags associated with that user's websites. I can't quite figure out where I'm messing up. Thank you.










share|improve this question




















  • 3





    what do you get from @user.tags?

    – G.B
    Jan 3 at 12:22











  • So I created a website with a tag of Travel and when I drop into pry and type Tag.last it gives me that as expected. But User.all[0].tags is giving me an empty array. I double checked that User.all[0] gives me the correct user that is creating the website/tag

    – Austin Burke
    Jan 3 at 12:34











  • Can you try User.first.tags.to_sql and see if it correctly joining the tables in sql?

    – punitcse
    Jan 3 at 12:38











  • So this is what it gave back: "SELECT "tags".* FROM "tags" INNER JOIN "websites" ON "tags"."website_id" = "websites"."id" WHERE " websites"."user_id" = 1"

    – Austin Burke
    Jan 3 at 12:51













  • Can you try current_user.tags.build(content: params[:dropdown], website: @website)? if that not work you can first save @website and then pass website id while building.

    – punitcse
    Jan 3 at 13:04














0












0








0








I'm setting up a User, Website, and Tag model, but am unsure of the correct associations?



This is a CRUD app in which I want to allow the User to create a 'website' (a bookmark essentially) and be able to add a 'tag' to that website so that websites can be filtered.



I have three tables: User, Website, Tag



I want, User to have many websites, website has many tags, tags belong to website, and a user has many tags through websites.



I already have the following models set up:



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


I am saving the tag via a post request:



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


When I check params at the binding.pry it gives me as expected:



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


My expectation is to be able to save an instance of a user and then use @user.tags to show all tags associated with that user's websites. I can't quite figure out where I'm messing up. Thank you.










share|improve this question
















I'm setting up a User, Website, and Tag model, but am unsure of the correct associations?



This is a CRUD app in which I want to allow the User to create a 'website' (a bookmark essentially) and be able to add a 'tag' to that website so that websites can be filtered.



I have three tables: User, Website, Tag



I want, User to have many websites, website has many tags, tags belong to website, and a user has many tags through websites.



I already have the following models set up:



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


I am saving the tag via a post request:



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


When I check params at the binding.pry it gives me as expected:



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


My expectation is to be able to save an instance of a user and then use @user.tags to show all tags associated with that user's websites. I can't quite figure out where I'm messing up. Thank you.







ruby-on-rails ruby activerecord sinatra sinatra-activerecord






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 14:53









ray

3,3731829




3,3731829










asked Jan 3 at 12:20









Austin BurkeAustin Burke

5717




5717








  • 3





    what do you get from @user.tags?

    – G.B
    Jan 3 at 12:22











  • So I created a website with a tag of Travel and when I drop into pry and type Tag.last it gives me that as expected. But User.all[0].tags is giving me an empty array. I double checked that User.all[0] gives me the correct user that is creating the website/tag

    – Austin Burke
    Jan 3 at 12:34











  • Can you try User.first.tags.to_sql and see if it correctly joining the tables in sql?

    – punitcse
    Jan 3 at 12:38











  • So this is what it gave back: "SELECT "tags".* FROM "tags" INNER JOIN "websites" ON "tags"."website_id" = "websites"."id" WHERE " websites"."user_id" = 1"

    – Austin Burke
    Jan 3 at 12:51













  • Can you try current_user.tags.build(content: params[:dropdown], website: @website)? if that not work you can first save @website and then pass website id while building.

    – punitcse
    Jan 3 at 13:04














  • 3





    what do you get from @user.tags?

    – G.B
    Jan 3 at 12:22











  • So I created a website with a tag of Travel and when I drop into pry and type Tag.last it gives me that as expected. But User.all[0].tags is giving me an empty array. I double checked that User.all[0] gives me the correct user that is creating the website/tag

    – Austin Burke
    Jan 3 at 12:34











  • Can you try User.first.tags.to_sql and see if it correctly joining the tables in sql?

    – punitcse
    Jan 3 at 12:38











  • So this is what it gave back: "SELECT "tags".* FROM "tags" INNER JOIN "websites" ON "tags"."website_id" = "websites"."id" WHERE " websites"."user_id" = 1"

    – Austin Burke
    Jan 3 at 12:51













  • Can you try current_user.tags.build(content: params[:dropdown], website: @website)? if that not work you can first save @website and then pass website id while building.

    – punitcse
    Jan 3 at 13:04








3




3





what do you get from @user.tags?

– G.B
Jan 3 at 12:22





what do you get from @user.tags?

– G.B
Jan 3 at 12:22













So I created a website with a tag of Travel and when I drop into pry and type Tag.last it gives me that as expected. But User.all[0].tags is giving me an empty array. I double checked that User.all[0] gives me the correct user that is creating the website/tag

– Austin Burke
Jan 3 at 12:34





So I created a website with a tag of Travel and when I drop into pry and type Tag.last it gives me that as expected. But User.all[0].tags is giving me an empty array. I double checked that User.all[0] gives me the correct user that is creating the website/tag

– Austin Burke
Jan 3 at 12:34













Can you try User.first.tags.to_sql and see if it correctly joining the tables in sql?

– punitcse
Jan 3 at 12:38





Can you try User.first.tags.to_sql and see if it correctly joining the tables in sql?

– punitcse
Jan 3 at 12:38













So this is what it gave back: "SELECT "tags".* FROM "tags" INNER JOIN "websites" ON "tags"."website_id" = "websites"."id" WHERE " websites"."user_id" = 1"

– Austin Burke
Jan 3 at 12:51







So this is what it gave back: "SELECT "tags".* FROM "tags" INNER JOIN "websites" ON "tags"."website_id" = "websites"."id" WHERE " websites"."user_id" = 1"

– Austin Burke
Jan 3 at 12:51















Can you try current_user.tags.build(content: params[:dropdown], website: @website)? if that not work you can first save @website and then pass website id while building.

– punitcse
Jan 3 at 13:04





Can you try current_user.tags.build(content: params[:dropdown], website: @website)? if that not work you can first save @website and then pass website id while building.

– punitcse
Jan 3 at 13:04












3 Answers
3






active

oldest

votes


















1














Read this Article and then try this:



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


If this doesn't work. Use scope in User model with



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





share|improve this answer


























  • No luck still. I shouldn't have to create a tags method if I'm using a join though should I?

    – Austin Burke
    Jan 3 at 12:53



















1














Consider a website 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


Query -



user = User.first
user.user_tags





share|improve this answer

































    1














    Try with following,



    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


    Query will look like, (for @user object)



    Tag.user_tags(@user)





    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54022200%2ftrouble-with-has-many-through-relationship%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Read this Article and then try this:



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


      If this doesn't work. Use scope in User model with



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





      share|improve this answer


























      • No luck still. I shouldn't have to create a tags method if I'm using a join though should I?

        – Austin Burke
        Jan 3 at 12:53
















      1














      Read this Article and then try this:



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


      If this doesn't work. Use scope in User model with



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





      share|improve this answer


























      • No luck still. I shouldn't have to create a tags method if I'm using a join though should I?

        – Austin Burke
        Jan 3 at 12:53














      1












      1








      1







      Read this Article and then try this:



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


      If this doesn't work. Use scope in User model with



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





      share|improve this answer















      Read this Article and then try this:



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


      If this doesn't work. Use scope in User model with



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






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jan 3 at 12:45

























      answered Jan 3 at 12:38









      G.BG.B

      2,94321540




      2,94321540













      • No luck still. I shouldn't have to create a tags method if I'm using a join though should I?

        – Austin Burke
        Jan 3 at 12:53



















      • No luck still. I shouldn't have to create a tags method if I'm using a join though should I?

        – Austin Burke
        Jan 3 at 12:53

















      No luck still. I shouldn't have to create a tags method if I'm using a join though should I?

      – Austin Burke
      Jan 3 at 12:53





      No luck still. I shouldn't have to create a tags method if I'm using a join though should I?

      – Austin Burke
      Jan 3 at 12:53













      1














      Consider a website 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


      Query -



      user = User.first
      user.user_tags





      share|improve this answer






























        1














        Consider a website 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


        Query -



        user = User.first
        user.user_tags





        share|improve this answer




























          1












          1








          1







          Consider a website 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


          Query -



          user = User.first
          user.user_tags





          share|improve this answer















          Consider a website 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


          Query -



          user = User.first
          user.user_tags






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 3 at 13:05

























          answered Jan 3 at 12:54









          GabbarGabbar

          4,5002518




          4,5002518























              1














              Try with following,



              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


              Query will look like, (for @user object)



              Tag.user_tags(@user)





              share|improve this answer




























                1














                Try with following,



                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


                Query will look like, (for @user object)



                Tag.user_tags(@user)





                share|improve this answer


























                  1












                  1








                  1







                  Try with following,



                  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


                  Query will look like, (for @user object)



                  Tag.user_tags(@user)





                  share|improve this answer













                  Try with following,



                  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


                  Query will look like, (for @user object)



                  Tag.user_tags(@user)






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 3 at 13:24









                  rayray

                  3,3731829




                  3,3731829






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54022200%2ftrouble-with-has-many-through-relationship%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith