I have problem with save data in DB.
This is my orders_controller:
def create
order = meal.build_order(order_params)
respond_with order
end
Function in orders factory:
o.create = function(order) {
return $http.post('/orders.json', order).success(function(data){
console.log(data);
o.orders.push(data);
});
};
Call orders.create in ordersCtrl (in angular controller)
if (!angular.isUndefined($scope.meal)) {
orders.create({
meal_id: $scope.meal.id,
status: "ordered",
});
}
What can be wrong with that code? When I've wrote order.save in Rails controller - order has been saved.
From the docs:
build_association(attributes = {})
Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key, but has not yet been saved.
So basically when you use build_order it is not saving it (and this is how rails works). You could use create_order.
Related
I have a form with checkboxes that get passed as an array "list_person_ids" on form submit. My models are "Occurance" which has an n:m relationship with "ListPerson" through the Model "Person". "list_person_ids" are saved in Person with the Occurance id and the ListPerson id.
I want to append one or more values to the array before this gets saved. The reason I need to do this is because the user can also add a new value in ListPerson using a textbox with the name "person_name".
def create
#occurance = Occurance.new(occurance_params)
add_person_id(#occurance)
...
# save
end
def add_person_id(object)
if params[:person_check] == '1'
object.list_person_ids.push( ListPerson.find_or_create_by(person: params[:person_name]).id )
end
end
def occurance_params
params.require(:occurance).permit(:person_check, :person_name, dim_person_ids: [])
end
find_or_create_by is successful, but nothing gets pushed to the array "list_person_ids". There is also no error message. Do I have to give permission somewhere to append this array? Please let me know if some information is missing.
on your model you can do something like below:
....
before_create :create_lists
private
def create_lists
ListPerson.find_or_create_by(list_person_ids: person_name.id)
end
I have a rails api, in which I'm using Active Model Serializers (version 0.10.6) to serializer json responses.
I have two arrays, both are of type "FeatureRequest" in an endpoint that returns a list of requests a user has made, and a second list of requests that a user is tagged in. Ideally, I'd like to serialize the response to look something like this:
{
"my_requests" : {
...each serialized request...
},
"tagged_requests" : {
...each serialized request, using the same serializer"
}
}
Is there some way to do this?
Here's my relevant controller method:
def index_for_user
user = User.includes(leagues: :feature_requests).find(params[:user_id])
# Find all requests that this user created
#users_created_feature_requests = FeatureRequest.requests_for_user(user.id)
#feature_requests_in_tagged_leagues = []
user.leagues.each do |league|
#feature_requests_in_tagged_leagues << league.feature_requests
end
...some serialized response here
end
In this code, the two lists are #users_created_feature_requests, and #feature_requests_in_tagged_leagues
Thanks!
Assuming you have a serializer like FeatureRequestSerializer, you can achieve that in the following way:
def index_for_user
user = ...
users_created_feature_requests = ...
feature_requests_in_tagged_leagues = user.leagues.map(&:feature_requests)
# serialized response
render json: {
my_requests: serialized_resource(users_created_feature_requests)
tagged_requests: serialized_resource(feature_requests_in_tagged_leagues)
}
end
private
def serialized_resource(collection, adapter = :attributes)
ActiveModelSerializers::SerializableResource.new(collection,
each_serializer: FeatureRequestSerializer,
adapter: adapter
).as_json
end
I'm trying to initialize an object, but I don't want to create the object to the database until the user has click saved. I've gotten this to work with the parent object only, but I can't seem to get my child objects to associate to the parent because I don't have an id yet for the parent object. What am I doing wrong in the code below? Thanks.
def new
# Build a new report object with the default type of "draft" and assign it to the player
report_options = { player_id: #player.id,
author_id: current_user.id,
position: #player.position,
type: "draft",
submitted: false }
#report = Report.new(report_options)
#skills.where('disabled = (?)',FALSE).each do |skill|
# On the line below I get an evaluation record with a proper skill id,
# but report_id is `nil` because I'm guessing the report hasn't been
# created yet. Is there a way to reserve an id for it without actually
# committing the record to the database until the user saves the record?
#report.evaluations.build(skill_id: skill.id)
end
end
The model of evaluations is not quite clear to me, but basically if you do something like
#report.evaluations.build
#skills.where('disabled = (?)', FALSE).each do |skill|
#report.evaluations << Evaluation.new(skill_id: skill.id)
end
it will add objects to evaluations without saving and won't require the report.id to exist at the moment of adding.
I'm trying to do that:
User upload file in first controller,
In some conditions I show page to user for choose element from file and pass file data to another controller in params: data#new
In data#new:
#elm_file = Rails.cache.read(params[:cache_id])
#elm_id = params[:index]
#user_name = params[:name]
new_elm_id = Elm.create_from_file #elm_file, #elm_id, #user_name
if new_elm_id != 0
redirect_to :action => '', :id => new_elm_id
end
return
in Model:
new_elm = Elm.new
return new_elm.id
The problem is - nothing returned. How can I record new element to database?
Your new action of the controller data returns nothing, because you haven't defined anything behind the return argument.
The two other lines, which are supposed to be from your model, returns nothing, because the id field is only set for persisted records. You maybe want to persist it with create().
I have controller with action new, and I want it to create ActiveRecord::Base descendant object, and write it into database (without showing it to user).
def new
active_order = current_user.orders.find {|o| o.status > 0 }
active_order = Order.new if active_order.nil?
(...)
end
Order.new creates local object, but my question is -- how to make Rails to fill it with default values and write to database?
You can write an unsaved ActiveRecord object instance to the database with the save method:
active_order = Order.new if active_order.nil?
active_order.save
It won't fill in the columns automatically, however. If you want to populate it with default values you can do this before calling save:
active_order = Order.new if active_order.nil?
active_order.field_name = "foo"
active_order.save
Or you can pass it in when you call new:
active_order = Order.new(:field_name => "foo") if active_order.nil?
active_order.save
If you want to do something fancier, you can have Rails automatically populate fields when you save by adding something like this to the model:
before_validation_on_create :set_default_values
def set_default_values
field_name = "foo" if field_name.blank?
end
you can use Order.Create(...) which will create a new object and persist it in the database (assuming Order is a child of ActiveBase of course)