سؤال

How can you post multiple entries at once time. For example

def create
    @visit = Visit.new(user_params)
    if @visit.save
        respond_with(@visit)
    else

    end
end

private

    def user_params
        params.require(:visit).permit(:room_id, :date)
    end

If this is your controller, and you send the following POST…

Content-Type = application/json

and

{
    "visit": 
        {
            "room_id": "7",
            "date": "2014-05-06"
        }
}

That will create 1 entry. How can you created say 3 entries at once? How do you write the JSON array of 3 visit entries, and how do you permit them properly in the controller?

هل كانت مفيدة؟

المحلول

You could do it by looping through the JSON hash you receive, saving each record as you go:

def create
    for visit in params[:visit] do
        new_visit = Visit.new(user_params)
        new_visit.save
    end
    redirect_to visits_path
end

private

def user_params
   params.require(:visit).permit(:room_id, :date) # => we'll need to fix this
end

The bottom line is that just because you're meant to send data in a specific way, doesn't mean you can't do it other ways. You can loop through passed params, allowing you to call the save method on each [:visit] param you pass

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top