Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8307027
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T18:26:49+00:00 2026-06-08T18:26:49+00:00

I’m banging my head against a Problem with AR Associations for 2 days now.

  • 0

I’m banging my head against a Problem with AR Associations for 2 days now. I know there is a easy solution to this but I can’t figure out.

I have two models Products and Users, that should be linked together. A Product should belong to a user and a user should have many products. I didn’t manage to set the user variable in my controller, so I went for a habtm association. Here are the models:

User.rb

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
#...

has_and_belongs_to_many :products

Product.rb

class Product < ActiveRecord::Base
has_many :product_images, :dependent => :destroy
accepts_nested_attributes_for :product_images, :allow_destroy => :true
has_and_belongs_to_many :users

products_controller.rb

class ProductsController < ApplicationController

def index
@products = Product.search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 10, :page => params[:page])

respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @products }
end
end

def new
@user = current_user
@product = Product.new#@user.products.build(params[:product])
@product.product_images.build
respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @product }
end
end

def create
@user = current_user
@product =  @user.products.build(params[:product])#Product.new(params[:product])
    @product.product_images.build
    @user.products << @product

respond_to do |format|
  if @product.save
    format.html { redirect_to @product, notice: 'Product was successfully created.' }
    format.json { render json: @product, status: :created, location: @product }
  else
    format.html { render action: "new" }
    format.json { render json: @product.errors, status: :unprocessable_entity }
  end
end
end

_form.html.erb

<%= form_for @product, :html => {:multipart => true, :class => 'form-horizontal'} do |f| %>

schema.rb

....
create_table "products_users", :id => false, :force => true do |t|
t.integer "product_id"
t.integer "user_id"
end
....

So, even I know, there should be a one-to-many association between user and product, this works out for me.
In IRB, I can do this:

u = User.first
u.products

with the habtm association I can even do it viseversa:

p = Product.first
p.users

But I can’t access the user attributes:

p.users.username:

NoMethodError:   User Load (2.0ms)  SELECT "users".* FROM "users" INNER JOIN "products_users" ON "users"."id" = "products_users"."user_id" WHERE "products_users"."product_id" = 12

Could anybody be so nice to help me out of this? What am I doing wrong?

Thanks a lot! Your help would save my weekend!

EDIT: Here’s my controller action for the one-to-many relation:

class ProductsController < ApplicationController

helper_method :sort_column, :sort_direction
def index
@products = Product.search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 10, :page => params[:page])

respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @products }
end

end

def show
@product = Product.find(params[:id])
@images = @product.product_images
respond_to do |format|
format.html # show.html.erb
format.json { render json: @product }
end
end

def new
@user = current_user
@product = Product.new#@user.products.build(params[:product])
@product.product_images.build
#3.times { @product.product_images.build }
respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @product }
end
end


def edit
@product = Product.find(params[:id])
    @product.product_images.build
end


def create
@user = current_user
@product =  @user.products.build(params[:product])#Product.new(params[:product])
    @product.product_images.build


respond_to do |format|
  if @product.save
    format.html { redirect_to @product, notice: 'Product was successfully created.' }
    format.json { render json: @product, status: :created, location: @product }
  else
    format.html { render action: "new" }
    format.json { render json: @product.errors, status: :unprocessable_entity }
  end
end
end


def update
@product = Product.find(params[:id])

respond_to do |format|
  if @product.update_attributes(params[:product])
    format.html { redirect_to @product, notice: 'Product was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render action: "edit" }
    format.json { render json: @product.errors, status: :unprocessable_entity }
  end
end
end


def destroy
 @product = Product.find(params[:id])
 @product.destroy

respond_to do |format|
  format.html { redirect_to products_url }
  format.json { head :no_content }
end
end

private
def sort_column
Product.column_names.include?(params[:sort]) ? params[:sort] : "created_at"
# params[:sort] || "created_at"
end

def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
# params[:direction] || "asc"
end
end

EDIT2: Schema.rb

create_table "products", :force => true do |t|
t.string   "title"
t.string   "description"
t.string   "testimonial"
t.decimal  "credits",       :precision => 3, :scale => 0
t.datetime "created_at",                                  :null => false
t.datetime "updated_at",                                  :null => false
t.decimal  "age"
t.string   "condition"
t.string   "product_image"
t.string   "image"
t.integer  "user_id"
end

create_table "users", :force => true do |t|
t.string   "email",                  :default => "", :null => false
t.string   "encrypted_password",     :default => "", :null => false
t.string   "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer  "sign_in_count",          :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string   "current_sign_in_ip"
t.string   "last_sign_in_ip"
t.datetime "created_at",                             :null => false
t.datetime "updated_at",                             :null => false
t.string   "username"
t.integer  "product_id"
end
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T18:26:51+00:00Added an answer on June 8, 2026 at 6:26 pm

    Don’t use a has_and_belongs_to_many if you have a one-to-many relation. Creating and maintaining another table is adding too much complexity. My advice would be to figure out why you can’t make the one-to-many relation working.

    You should be able to make this work :

    class User < ActiveRecord::Base
      has_many :products #Plural
    end
    
    
    class Product < ActiveRecord::Base
      belongs_to :user #Singular
    end
    

    If it doesn’t work, copy/paste your controller code that you use for one-to-many relation!

    Good luck

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Does anyone know how can I replace this 2 symbol below from the string
I know there's a lot of other questions out there that deal with this
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I have this code to decode numeric html entities to the UTF8 equivalent character.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.