0

In Model-1 scaffold create action,

 def create
  @auclub = Auclub.new(auclub_params)
  user = User.find(current_user.id)
  respond_to do |format|
    if @auclub.save && user.update(auclub_id: @auclub.id)
      format.html { redirect_to @auclub, notice: 'Auclub was successfully created.' }
      format.json { render :show, status: :created, location: @auclub }
    else
       //some codes
    end
  end
end

and and i want create club with user

this code works, but if i use like this

user = User.find(current_user.id)
user.new(auclub_id : @auclub.id)
user.save

it doesn't works! is there any differences between update and new.save?

PrepareFor
  • 2,448
  • 6
  • 22
  • 36

2 Answers2

2

try :

  @auclub = Auclub.new(auclub_params)
  @user = User.find(current_user.id)
  @auclub.save
  @user.auclub_id = @auclub.id
  @user.save

Know more APi dock

vipin
  • 2,374
  • 1
  • 19
  • 36
0

You are doing things in a wrong way.

Without model and other codes, I can suggest to do like this:

user = User.find(current_user.id)
user.auclub_id = @auclub.id
user.save

And I think there is no new method available for an ActiveRecord instance like user in your case.

new is used on ActiveRecord class to create a new instance like:

user = User.new

And I don't think there is much difference between using update method and manually reassigning an attribute and saving the object using save method but you have to keep an eye on performance, DRY principle and callbacks defined on model.

Sajan
  • 1,893
  • 2
  • 19
  • 39