Skip to main content

How do i save a field in a separate table?

Rails • Asked by Alan Reid

Hi all,
I want to save the brand_id i am creating in my users table how would i go about doing this? I currently have my code saving the brand.

def create
    @brand = Brand.new(brand_params)
    if @brand.save
      flash[:success] = "Brand added!! :D"
      redirect_to root_url
    else
      render 'new'
    end
  end

Just thought that maybe I should use a branduser table so a user can have multiple brands. Would this be better? and how would i join these together?


Yep, if every user needs multiple brands, you'll need a BrandUser model (or UserBrand, whichever is clearer) in order to do that.

Then if you've got your associations setup, you can change your first line to the following which will automatically create the join record for you.

@brand = current_user.brands.new(brand_params)

That will require you to have these associations:

class User
  has_many :brand_users
  has_many :brands, through: :brand_users
end

class Brand
  has_many :brand_users
  has_many :users
end

class BrandUser
  belongs_to :brand
  belongs_to :user
end

Know what mate, i am sure you said about this before when i was discussing the structure of the DB lol Thanks again buddy.


Haha you know I think we might have! Never hurts to talk about it again though. :)


I am getting this error, what could i be missing?

NameError in BrandsController#create
uninitialized constant User::UserBrand

def create
    @brand = current_user.brands.new(brand_params)  <--- this line?
    if @brand.save
      flash[:success] = "Brand added!! :D"
      redirect_to root_url

Did you create your UserBrand model? or did you name it like I showed as BrandUser?


Ok I had created my model wrong Userbrands instead of UserBrands.

Its now creating the brand still, but not adding in the user_id and brand_id to the user_brands table


I have this...

class User < ApplicationRecord
  has_many :user_brands
  has_many :brands, through: :user_brands
class UserBrand < ApplicationRecord
  belongs_to :brand
  belongs_to :user
class Brand < ApplicationRecord
  has_many :user_brands
  has_many :users
  has_many :products
  mount_uploader :logo, PictureUploader

My migration was like this...

class CreateUserBrands < ActiveRecord::Migration[5.0]
  def change
    create_table :user_brands do |t|
      t.references :user, foreign_key: true
      t.references :brand, foreign_key: true

      t.timestamps
    end
  end
end

My create method

def create
    @brand = current_user.brands.new(brand_params)
    if @brand.save
      flash[:success] = "Brand added!! :D"
      redirect_to root_url
    else
      render 'new'
    end
  end

That looks correct. Everything working now?


na its not saving in the user_brands table but is saving the brand lol

I have reloaded the server too using rails s


Hmm, that shouldn't be possible because of creating it through the association. Print out the brand before the save or byebug it to inspect and make sure it has the association setup in memory and the @brand.user_brands record as well.


i get this...

(byebug) @brand.user_brands
#<ActiveRecord::Associations::CollectionProxy []>
(byebug)

Hmm, welp, there's something definitely wrong then. I did notice your Brand model was missing the through association on this: has_many :users, through: :user_brands. Possibly that's it? I didn't think that was required, but maybe...


sorted it :D
so its actually @brand = current_user.brands.create(brand_params) instead of new


Now i have that sorted, i need to find out how to get the names of the brands for that user so that i can populate a select dropdown haha


Awesome! check out collection_select for that dropdown btw. :)


hehehe :D <%= collection_select(:brand_id, 0, current_user.brands.all, :id, :name) %>

this is why i love Rails! that would take hours of coding in .NET!!


I know right?! :)


Hi,
I am trying to make sure a user is allowed to edit a product, however I'm not sure how i can check the user_brands table.

I have this check for the brands...

# Confirms the correct user.
    def user_allowed
      #Check to see if the user is allowed to access this brand
      @brands = current_user.brands.find_by(id: params[:id])
      # If they are not redirect them to thier brands managment page.
      redirect_to(brands_path) if @brands.nil?
    end

How would i go about checking that a user is allowed to edit a brand? I have this which gets all products for a brand

@brand = Brand.find(params[:id])
@products = @brand.products.all

Hi,
I am trying to make sure a user is allowed to edit a product, however I'm not sure how i can check the user_brands table.

I have this check for the brands...

# Confirms the correct user.
    def user_allowed
      #Check to see if the user is allowed to access this brand
      @brands = current_user.brands.find_by(id: params[:id])
      # If they are not redirect them to thier brands managment page.
      redirect_to(brands_path) if @brands.nil?
    end

How would i go about checking that a user is allowed to edit a brand? I have this which gets all products for a brand

@brand = Brand.find(params[:id])
@products = @brand.products.all

Hey Alan,

That's a pretty good way of doing it. The logic is that if a user isn't connected to a brand, then don't allow them to edit. The current_user.brands.find actually uses the join table because you're using the association. The only thing you'd need to access current_user.user_brands directly for would be if you were to add and check for roles on that table. Without roles, you can assume that if the role exists, then the user has access to that brand.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.