Home>

I don't know: how to add a category when creating a new Post.

Premise: There are Post model and Catgeory model. The Post model has title, content, and category_id columns, and is associated with the Category model.

<What I don't know specifically>
/ posts/new
The following form was created using form_for.

Set category_id with a numeric value in the field "Category" in the image of the above form

&lt;% = form_for (@post) do | f |%&gt;
   &lt;% = f.label: title%&gt;
   &lt;% = f.text_field: title%&gt;
   &lt;% = f.label: content%&gt;
   &lt;% = f.text_field: content, size: 50%&gt;
   &lt;% = f.label: category%&gt;
   &lt;% = f.number_field: category%&gt;
   &lt;% = f.submit "Submit"%&gt;
   &lt;% end%&gt;


Then move to the controller.

class PostsController&lt;ApplicationController
  def new
    @ post = Post.new
  end
  def create
    category = Category.find (category_params)
    @ post = category.posts.build (post_params)
    if @ post.save
      render 'normal/home'
  else
    redirect_to root_url
  end
end

  private
  def category_params
    params.require (: post) .permit (: category_id)
  end
  def post_params
    params.require (: post) .permit (: title,: content)
  end
end

At this time, category_id is not entered for some reason. It is tripped on the first line of create.

category = Category.find (2)


When it was, it went well.

I would be happy to tell you why the value of category_id is not included!
I did not understand even after examining.

I would appreciate your reply.

  • Answer # 1

    I'm sorry, there were too few explanations.

    category = Category.find_by (id: category_params)


    Not

    category = Category.find_by (category_params)


    How about doing this?

    The parameter is a hash value, not just a value.
    The contents are hoge: huga.
    So, if you put a hash value in find that takes only a numeric value as an argument, will you get an error?

    If you are wrong, I'm sorry.

    or

    category = Category.find (category_params [: category_id])


    Is n’t this too?

  • Answer # 2

    How about find_by?

Related articles