Ask A Question


You’re not receiving notifications from this thread.

How do i save a field in a separate table?

Alan Reid asked in Rails

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?

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.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,168+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.