I have a form for two object User Board
Here is my controller:
def create
@board = Board.new(params[:board])
@user = User.new(params[:user])
respond_to do |format|
if (@user.save and @board.save)
format.js {redirect_to some_path}
else
format.js {render :action => "new" }
end
end
end
I don't want to save either one unless both are valid. And I want to show the error messages for both at one time on the form.
I have tried all types of combinations of '&&' '&' 'and' but they don't give me the result I w开发者_C百科ant. They show the errors of one object while saving the other.
How can I do this properly?
&&
doesn't work like &&
in Linux.
You have two alternatives. You can check whether the records are valid?
, then perform the save.
def create
@board = Board.new(params[:board])
@user = User.new(params[:user])
respond_to do |format|
if @user.valid? && @board.valid?
@user.save!
@board.save!
format.js { redirect_to some_path }
else
# do something with #errors.
# You check the existence of errors with
# @user.errors.any?
# @board.errors.any?
# and you access the errors with
# @user.errors
# @board.errors
format.js { render :action => "new" }
end
end
end
or if your database supports transactions, use transactions.
def create
@board = Board.new(params[:board])
@user = User.new(params[:user])
respond_to do |format|
begin
transaction { @user.save! && @board.save! }
format.js { redirect_to some_path }
rescue ActiveRecord::RecordInvalid
format.js { redirect_to some_path }
end
end
end
Personally, I would check for valid?
.
If you look in the source code of the save method of ActiveRecord you see:
def save(options={})
perform_validations(options) ? super : false
end
What you want to do, is running the perform_validations manually before calling save. For this, you can use the valid? method from ActiveResource. You can find the documentation here:
http://api.rubyonrails.org/classes/ActiveRecord/Validations.html#method-i-valid-3F
精彩评论