Reputation: 892
I need to make new associations for Modification
model if.save
. Also these associations need to be same as related Entity
model has. But i'm getting this error:
When assigning attributes, you must pass a hash as an argument.
ModificationController.rb
def create
@modification = Modification.new(change_params)
respond_to do |format|
if @modification.save
@modification.entity.boxes.each do |d|
@modification.boxes.new(d)
end
flash[:success] = "Success"
format.html { redirect_to @modification }
format.json { render :show, status: :created, location: @modification }
else
format.html { render :new }
format.json { render json: @modification.errors, status: :unprocessable_entity }
end
end
end
More info:
Each Modification
belongs_to Entity
Both Modifications
and Entities
has_many Boxes
.
Upvotes: 3
Views: 86
Reputation: 9586
So you want to create a new box association using an existing Box
. We can grab the attributes of the existing box to create the new one. However, an existing box will already have an id
, so we need to exclude that from the attributes.
Following the above logic, the following should work:
def create
@modification = Modification.new(change_params)
respond_to do |format|
if @modification.save
@modification.entity.boxes.each do |d|
@modification.boxes << d.dup
end
flash[:success] = "Success"
format.html { redirect_to @modification }
format.json { render :show, status: :created, location: @modification }
else
format.html { render :new }
format.json { render json: @modification.errors, status: :unprocessable_entity }
end
end
end
Upvotes: 2
Reputation: 10368
When you declare a has_many association, the declaring class automatically gains 16 methods related to the association as the mention Guide Ruby On Rails Association Has-Many
def create
@modification = Modification.new(change_params)
respond_to do |format|
if @modification.save
@modification.entity.boxes.each do |d|
@modification.boxes << d # if d.present? use if condition there is nay validation in your model.
end
flash[:success] = "Success"
format.html { redirect_to @modification }
format.json { render :show, status: :created, location: @modification }
else
format.html { render :new }
format.json { render json: @modification.errors, status: :unprocessable_entity }
end
end
end
Hope this helo you !!!
Upvotes: 1