0

I am learning about 'where' in Rails 3 and I am wondering why my code is giving me a NoMethod Error.

  def create
    #get form values from 'new' page
    @post = Post.new(params[:post])

    #search for the inventory item with the sku code the user typed in the form
    @item = Inventory.where(:sku_code => @post.sku_code)

    #set post variable to a variable from the row with the sku code
    @post.detail = @item.detail

    @post.save
  end

By searching the SKU, I want to retrieve the other variables in the same id and set them to my @post variable. Anyone able to give me a hand?

0

1 Answer 1

1

Assuming that SKU code is unique, you got to do it like this

@post = Post.new(params[:post])

@post.detail = Inventory.where(:sku_code => @post.sku_code).first.try(:detail)

first will fetch the first (and possibly only) record from the database. try will try to fetch detail if the returned Inventory was not nil.

Check this blog post to learn more about try method.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for responding. I checked the references and they are correct. It is giving me a Template is missing error: Missing template posts/create, application/create. Any ideas?
Usually you want to redirect after creation, for example to the show action. Or show the form again by rendering new if the post cannot be saved. See as well guides.rubyonrails.org/getting_started.html#creating-new-posts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.