merrua
merrua

Reputation: 585

ActiveModel::MissingAttributeError in Rails4 Controller #create

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

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

Upvotes: 1

Views: 461

Answers (1)

seancdavis
seancdavis

Reputation: 2821

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.

Upvotes: 2

Related Questions