Reputation: 841
I am confused how to best update data from an associated model in rails with an angular front end (although this is more of a rails issue really).
Say I have a model called votable which some attributes (start_date, end_Date) and has_many texts (descriptions of the votable in different languages)
class Votable < ActiveRecord::Base
has_many :votable_texts
accepts_nested_attributes_for :votable_texts
end
The show method in my controller generates json data that I use in angular to build the form:
def show
respond_to do |format|
format.json {
render :json => @votable.to_json(
:except => [:created_at, :updated_at],
:include => {
:votable_texts => {
:except => [:created_at, :updated_at]
}
}
)
}
end
end
This generates something like the following json:
{
"id": 2,
"start_date": "2015-02-05T00:00:00.000Z",
"end_date": "2016-02-02T00:00:00.000Z",
"votable_texts": [
{
"id": 6,
"votable_id": 2,
"locale": "nl",
"issue": "Test"
},
{
"id": 2,
"votable_id": 2,
"locale": "en",
"issue": "Test"
}
]
}
On the angular side I read this json into a variable and use ng-model for binding this data to my form. When the user hits the save button I use $http.put to post this data back to rails (in the same structure as the json generated by rails).
The thing is that the attributes of the votable model do get updated (for example start_date), but those that are in the nested votable_texts model are not updated.
The relevant pieces of the controller look like this:
def update
respond_to do |format|
if @votable.update(votable_params)
format.json { render :show, status: :ok, location: @votable }
else
format.json { render json: @votable.errors, status: :unprocessable_entity }
end
end
end
private
def votable_params
params.permit(:id, :start_date, :end_date, :votable_texts)
end
What am I missing? Do I need to handle the updates of the association myself manually? How is this best done?
Thanks!
Upvotes: 1
Views: 616
Reputation: 1980
I think your issue is because you need to permit the nested parameters of the votable_texts
model. However when using accepts_nested_attributes_for
and update
Rails is going to expect you to pass voteable_texts_attributes
in order for it to update the associated records. In this case you would have the following.
params.permit(:id, :start_date, :end_date, votable_texts_attributes: [:id, :voteable_id, :locale, :issue])
So you may need to update the show action to use voteable_texts_attributes
or if not you're going to have to change the param key somewhere along the line.
Upvotes: 1