Question

I am rather new to rails and programming in general. I feel I have picked up the rails MVC and other concepts pretty well but still have a hard time figuring out the syntax of what goes into controller actions. For example when you create a

def edit

end

How do you know how to format the contents/inside of that method.

Thus far I have seen alot of this:

def new
  @product = Product.new
end

If I understand this correctly this is creating an instance of the Product Model and putting it into an instance variable that is accessible by the "new" view in products/view

But let's say I want to edit that. My inclination is to do add the following action in the controller:

def edit
  @product = Product.edit
end

I'm not sure the syntax Product.edit is correct though, not sure how to differentiate between edit and update either. How do I know what calls on my Model Object when creating instance variables? Is there somewhere online I can go to learn this? I have found no where thus far with a good list of commands I can play with.

Was it helpful?

Solution

def edit
  @product = Product.edit
end

should be

def edit
  @product = Product.find(params[:id])
end

simple explanation

The edit action (#method) is called when you call e.q localhost:3000/products/1/edit

the 1 is the id of your product which is passed to your controller and can be accessed by using params.

when the user hit edit . It is ussually send the data to update action

def update
  @product = Product.find(params[:id])
  @product.update(params[:product].permit(:title, :desc))
end

Ok i know i'm not explain it good enough. You really need to read this

http://guides.rubyonrails.org/

OTHER TIPS

To edit something, first you need to have (or get, or create, or etc...) it. In the new method, you just create new instance of Product, this is not necessary, but needs for *form_for* helper, and generally good practice, because it you can use same form for creating and editing. Product.new just creates new product and initialize its fields with default values. Product.find searches product (single) in database by id and returns it. So for editing you first need to find your product, then it will be used to fill fields in editing form, and than in update method you will update it:

def update
  target_product_required
  @product.assign_attributes(product_params)

  if @product.save
    redirect_to @product
  else
    render :edit
  end
end

def target_product_required
  @product ||= Product.find(params[:id])
end

def product_params
  params.require(:product).permit(:title, :description, :price, :available_quantity, :image, :remote_image_url)
end

This is common pattern: target_product_required returns/assigns founded by id in params product to instance variable, product_params returns product specified params. More about this read in http://guides.rubyonrails.org/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top