Insert data into 2 tables from 1 controller
I have scaffold
with 2 fields name:string, active:boolean.开发者_Go百科.
This way scaffold create data...
def create
@question = Question.new(params[:question])
render :json => @question.to_ext_json(:success => @question.save)
end
Everything's good, but i want when creates question some data inserting into my another table called tokens:
In my token table there are only 2 fields: token & is_active (boolean)
def create
@w = "token"
@question = Question.new(params[:question])
@token = Token.new({:token => @w, :is_active=>"1"})
render :json => @question.to_ext_json(:success => @question.save)
end
this way doesn't work. How i can do this?
Something like...
def create
@w = "token"
@question = Question.new(params[:question])
if success = @question.save
@token = Token.new({:token => @w, :is_active=>"1"})
@token.save
end
render :json => @question.to_ext_json(:success => success)
end
This assumes any validation is done on the Question model. You could take this even further and use a Transaction, but that seems needlessly complicated in this case.
精彩评论