ruby on rails 4 - ActiveRecord nested value update fails -


i trying update product please see code below. can't seem update category. welcome.

product model:

class product < activerecord::base   belongs_to :category    accepts_nested_attributes_for :category    def category_name     category.try(:name)   end    def category_name=(name)     category.find_or_create_by(name: name) if name.present?   end end 

category model:

class category < activerecord::base   has_many :products end 

products controller:

class productscontroller < applicationcontroller   def index     @products = product.all   end    def show     @product = product.find(params[:id])   end    def edit     @product = product.find(params[:id])   end    def update      @product = product.find(params[:id])      @product.update(products_params)      redirect_to @product   end    private    def products_params     products_params = params.require(:product).permit(:name, :category_id, category_attributes: [:category_name])   end end 

you creating setter inside product class passing attribute nested model. should chose 1 of solutions. best 1 delegate in rails nester attribute handling.

http://api.rubyonrails.org/classes/activerecord/nestedattributes/classmethods.html

class product < activerecord::base   belongs_to :category   accepts_nested_attributes_for :category end  class category < activerecord::base   has_many :products end  class productscontroller < applicationcontroller   def index     @products = product.all   end    def show     @product = product.find(params[:id])   end    def edit     @product = product.find(params[:id])   end    def update      @product = product.find(params[:id])      @product.update(products_params)      redirect_to @product   end    private    def products_params     params.require(:product).permit(:name, category_attributes: [:name])   end end 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -