Home>

I am currently creating an app with Ruby on Rails and would like to be able to post and save notes and photos using form_with.
When I set up an association, created a table, and posted it, the following error occurred.
I want to resolve this error so that I can save the posted data.

ActiveModel :: MissingAttributeError in ItemsController # new
can't write unknown attribute `post_id`
Extracted source (around line # 12):

  def new
    @item = Item.new
    @ item.build_post
    @post = Post.new (post_params)
  end

Application Trace | Framework Trace | Full Trace
app/controllers/items_controller.rb: 12: in `new'
Request
Parameters:
None
Toggle session dump
Toggle env dump
Response
Headers:
None
items_controller.rb
class ItemsController  @ post.img_identifier)
  end
  private
  def item_params
    params.require (: item) .permit (: image,: memo, post_attributes: [: id ,: img ,: item_id]). merge (user_id: current_user.id)
  end
  def set_item
    @item = Item.find (params [: id])
  end
  def move_to_index
    unless user_signed_in?
      redirect_to action :: index
    end
  end
  def post_params
    params.permit (: img)
  end
end
models/item.rb
class Item</pre>
<strong>models/post.rb</strong>
<pre><code>class Post</pre>
<strong>view/items/_form.html.haml</strong>
<pre><code>= form_with (model: item, local: true) do | form |
  = form.text_area: memo, pleaceholder: "memo", rows: "10"
  = form.file_field: img
  = form.submit "SEND"
Supplementary information (FW/tool version, etc.)

I am creating an app by trial and error on my own, and there may be some mistakes such as how to set up an association.
We are not currently working on it, so we would appreciate it if you could give us some advice.
I look forward to working with you.

  • Answer # 1

    solved.

    Modification place

    By changing the place where belongs_to: post in item.rb of model to has_one: post, the error was improved and I was able to post.

    Reason for error

    Since belongs_to means to be subordinate, and has_one seems to have one target, so be careful when incorporating Assiciation after that.