1

When I submit my form I'm seeing this error.

 NoMethodError in SellersController#create 
undefined method `sellers' for #
 match = match_attribute_method?(method.to_s)
 match ? attribute_missing(match, *args, &block) : super

It's coming from this line in the sellers_controller.rb

def create
  @seller = current_user.sellers.build(seller_params)  
end  

Relevant part of the model:

class Seller < ActiveRecord::Base
  belongs_to :user
end

View: new.html.erb

<%= form_for(@seller) do |f| %>
...      
<% end %>

Rake routes runs without an error.

I'm missing something with how rails assumes the db/view/model is for my controller. I've been looking through the documentation but nothing is coming to mind.

routes.rb

 Rails.application.routes.draw do
   resources :sellers
 end

create_sellers.rb

class CreateSellers < ActiveRecord::Migration
  def change
    create_table :sellers do |t|
      ....
        t.references :user, index:true, foreign_key: true

I've already tried

  • restarting rails
  • closing and reopening the terminal
  • rolling back the migration and trying it again (no error on migration)

I've looked at the migration/model/controller view and I am not seeing the problem (so Its probably there and obvious).

user.rb

class User < ActiveRecord::Base
  has_one :seller
end
kalelc
  • 1,507
  • 1
  • 18
  • 33
merrua
  • 575
  • 1
  • 4
  • 11
  • 1
    `user.rb` has `has_many sellers`? – kalelc Nov 23 '15 at 20:28
  • see above, a user has one seller. a seller belongs to a user in the models. Looks like the edit lost it – merrua Nov 23 '15 at 20:32
  • Can you show your user model? – x6iae Nov 23 '15 at 20:35
  • 1
    if a _a user has one seller_ then why you call `current_user.sellers` ? would not be `current_user.seller` ? – kalelc Nov 23 '15 at 20:42
  • @ kalelc I've tried that, but I just get this error then. "undefined method `build' for nil:NilClass, @seller = current_user.seller.build(seller_params) " – merrua Nov 23 '15 at 20:44
  • 1
    Seller model has `build` method? – kalelc Nov 23 '15 at 20:47
  • build should be another way of saying new, but google is telling me, build should only be used with a collection. so that might be it, trying it now – merrua Nov 23 '15 at 20:53
  • 1
    Try in your rails console `User.first.seller.inspect` – kalelc Nov 23 '15 at 21:00
  • @kalelc thanks. Along with the extra s, it was just the build syntax is different for has_one than has_many. Between your help and the comment below this is resolved. – merrua Nov 23 '15 at 21:01

1 Answers1

2

If a user has one seller, then you need to change the way you build the association:

@seller = current_user.build_seller(seller_params)

Check out this answer that compares the build syntax for has_many and has_one.

Community
  • 1
  • 1
seancdavis
  • 2,739
  • 2
  • 26
  • 36