开发者

Can I save data in more that one time for single request in rails?

开发者 https://www.devze.com 2023-03-24 16:44 出处:网络
There is model call Event which contains following attributes start_at, end_at, details, trainer This is my normal create method which generated my scaffold command

There is model call Event which contains following attributes

start_at, end_at, details, trainer

This is my normal create method which generated my scaffold command

  def create
@event = Event.new(params[:event])

respond_to do |format|
  if @event.save
    format.html {开发者_如何学C redirect_to(@event, :notice => 'Event was successfully created.') }
    format.xml  { render :xml => @event, :status => :created, :location => @event }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @event.errors, :status => :unprocessable_entity }
  end
 end
end

and I need to modify this as follows when particular event object have date gap between stat_at and end_at more than 6 I need to save that event as two events. First event will started at original started date and end date should be middle date of the event and other data are same. But in second event it should be start date as middle date and end date should have original end date. Can some one explain how could I done this???


After the line if @event.save you can create another Event record like this

Please note this code is untested.

if (@event.end_at - @event.start_at) > 6
  event2 = Event.new
  event2.start_at = something
  event2.end_at = anotherthing
  event2.save
end


As you are going to do some logic, you can write a method to perform your logic and call that method from controller. Better keep the method in Event model to satisfy good practice of Fat Model and Lean Controller.

def self.create_event(ev_params)
  status = false
  if event.end_dat - event.stat_dat >6
    # create two events
    event1 = Event.new(ev_params)
    mid_date = event1.stat_at + ((event.end_dat - event.stat_dat)/2).days
    event1.end_at = mid_date
    event2 = Event.new(ev_params)
    event2.stat_at = mid_date
    status = event1.save'
    status = event=2.save'
  else
    status = Event.create(ev_params)
  end
  status      
end

And call this method from controller Event.create_event in controller @event.save.

This is not tested code but I hope you can easily get from above code.

0

精彩评论

暂无评论...
验证码 换一张
取 消