Reputation: 1619
I am trying to implement a comment feature for a site. So far, I am able to pass the movie_id
of the movie I want to comment to, to the page where I create the comment (which is the default scaffold view). After that, I try to pass the movie_id
to the create
method of the comments_controller
but it will not pass. I tried assigning its class (params[:movie_id].class
) to the comment
attribute and it says NilClass
.
My code:
comments_controller.rb
def create
@comment = Comment.new
@comment.comment = params[:comment].values.first
@comment.user_id = current_user.id
@comment.movie_id = params[:movie_id]
#...
end
_form.html.erb
(The one the new
page renders)
<%= simple_form_for(@comment) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :comment, label: false, placeholder: 'Your opinion'%>
<%= f.hidden_field :movie_id, input_html: { value: params[:movie_id] } %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
The params[:movie_id]
in the html
file, is actually what I want it to be, I tried adding it as a placeholder and it has the correct value.
This will probably be a stupid mistake but, I am really stuck...
Thanks for your time.
Upvotes: 1
Views: 2973
Reputation: 3515
You have an error in your html. The hidden field should either use proper rails syntax for a hidden field, or use simple form syntax.
Rails syntax:
<%= f.hidden_field :movie_id, value: params[:movie_id] %>
Simple form syntax:
<%= f.input :movie_id, as: :hidden, input_html: { value: params[:movie_id] } %>
In controller:
@comment.movie_id = params[:comment][:movie_id]
Btw, its good form to use strong parameters as follows
@comment.movie_id = comment_params[:movie_id]
private
def comment_params
params.require(:comment).permit(:movie_id, ...(and others..)
end
Upvotes: 1
Reputation: 2290
<%= f.hidden_field :movie_id, params[:movie_id] %>
This should work?
I would nonetheless do, since in the controller you probably have @comment = Comment.new
to use the form_for, @comment.movie_id = params[:movie_id]
in the controller and then use @comment.movie_id
in the form, just to have it cleaner?
Upvotes: 0