PrepareFor
PrepareFor

Reputation: 2598

rails why model new().save doesn't work in create action

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?

Upvotes: 0

Views: 1086

Answers (2)

vipin
vipin

Reputation: 2510

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

Upvotes: 2

Sajan
Sajan

Reputation: 1923

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.

Upvotes: 0

Related Questions