Reputation: 2847
This code successfully creates a new Notice, as intended:
In the submit form:
<%= form_tag( {controller: "notices", action: "create"}, method: "post", class: "comment_form", html: { multipart: true } ) do %>
.
<%= hidden_field_tag "notice[supernotice][commentee_id]", notice.id %>
.
<% end %>
In the notices_controller.rb:
def create
@character = Character.find_by(callsign: params[:callsign])
@notice = @character.notices.build(notice_params)
if @notice.save
if !params[:notice][:supernotice][:commentee_id].nil?
@notice.create_comment(params[:notice][:supernotice][:commentee_id]) # hits the create_comment method in notice.rb
end
end
def notice_params
params.require(:notice).permit(:content, :picture, :latitude, :longitude, supernotice_attributes: [:commentee_id] )
end
Class notice.rb:
has_one :supernotice, through: :active_comment_relationship, source: :commentee
accepts_nested_attributes_for :supernotice
def create_comment(other_notice_id)
create_active_comment_relationship(commentee_id: other_notice_id)
end
However, the logs show the error: Unpermitted parameter: supernotice
. How do I get rid of this error? What is wrong with the way I am submitting the nested parameter?
Upvotes: 1
Views: 754
Reputation:
You can try this:
<%= hidden_field_tag "notice[supernotice_attributes][0][commentee_id]", notice.id %>
But in general, the way you create your nested attributes is wrong. You should start with the form_for helper, and then for nested attributes use f.fields_for helper. For example:
<%= form_for @notice do |f| %>
<%= f.fields_for :supernotice do |ff| %>
<%= ff.hidden_field :commentee_id, @notice.id %>
<% end %>
<% end %>
One more thing. If you create your form in the way I proposed, most likely you will not need that hidden field at all because rails will take care of it. Meaning, during creation rails will know what id to populate on commentee_id.
Upvotes: 3