Ruby on rails NoMethodError in controller after create an association -


i have 2 models user , promotion, user can create has_many promotion , promotion belong user :

promotion.rb

class promotion < activerecord::base belongs_to :user belongs_to :good  validates :name,  :presence => true validates :title, :presence => true validates :description, :presence => true   end 

for users used devise so:

user.rb

class user < activerecord::base  has_many :promotions  ,:foreign_key => "user_id",    :dependent => :destroy    devise :database_authenticatable, :registerable,      :recoverable, :rememberable, :trackable, :validatable,      :omniauthable, :omniauth_providers => [:facebook] # setup accessible (or protected) attributes model  attr_accessible :email, :password, :password_confirmation, :remember_me,:provider,:uid,:address,:name,:surname,:supplier,:partita_iva,:state,               :gender ,:language,:bio,:work,:education 

now when want create new promotions error

nomethoderror in promotionscontroller#create undefined method `promotions' nil:nilclass

this controller:

 def create @user = user.find_by_id(params[:user_id]) @promotion =@user.promotions.create(:params[:promotion]) redirect_to promotion_patch(@promotion)  respond_to |format|   if @promotion.save     format.html { redirect_to @promotion, notice: 'promotion created.' }     format.json { render json: @promotion, status: :created, location: @promotion }   else     format.html { render action: "new" }     format.json { render json: @promotion.errors, status: :unprocessable_entity }   end end end 

help please :)

it looks though params[:user_id] did not contain valid user id. since used find_by_id instead of find, quietly assigned nil @user, , of course nil doesn't have method named #promotions, line failed.

you need either check @user being nil, or change user.find_by_id user.find , rescue activerecord::recordnotfound. in either case, respond custom 404 or whatever other way seems appropriate.

one other question, intention user can create promotions other user? if should creating promotions themselves, can avoid whole mess eliminating whole user.find_by_id line, , changing next line to:

@promotion = current_user.promotions.create(params[:promotion]) 

devise should have current_user you. in case, need handle happens if promotion cannot created because there validation errors in user-supplied parameters.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -