Ari Ticas
Ari Ticas

Reputation: 27

Ruby on Rails link_to method to change db value

Hello I am trying to change a string value from "no" to "yes" in my Rails Postgresql db based on if a user clicks a yes or no button using the link_to method in my view. I have designated the default string value to "no" so I would like the value to change to yes if a user clicks the yes button . I would like assign the 'link_to method' to the yesmarried action in my controller.I =m not sure how to locate the the newcase in the yesmarried action and I keep getting the error Couldn't find Newcase without an ID

here is my controller

class NewcaseController < ApplicationController
  def new
  end
  
  def create
      @newcase = NewCase.new(newcase_params)
  end
  def yesmarried
     @newcase=Newcase.find(params[:id])
        self.married = "yes"
  end
  private
  def newcase_params
      params.require(:newcase).permit(:state,:first_name,:last_name, :dob, :email, :telephone_number, :addr,:respondent_fname, :respondent_lname,:respondent_addr, :marriage_date, :state_of_marriage, :date_of_seperation, :number_of_children, :children_addr, :occupation , :work_addr, :net_monthly, :married)
  end
end

here is my view:

<%=link_to 'yes',new_path(@newcase), class:"btn btn-lg rounded btn-warning", action: "yesmarried",method: "put", "data-toggle" => "modal", 'data-target' => '#married-question', "data-bs-dismiss"=>"modal"  %>

routes file:

get '/new', to:'newcase#new'
post '/new', to:'newcase#create'
patch '/new', to:'newcase#yesmarried'
put '/new', to:'newcase#yesmarried'

Upvotes: 0

Views: 314

Answers (1)

t56k
t56k

Reputation: 7011

Your code is a little unrestful and non-idiomatic but your yesmarried method should read:

def yes_married
  @newcase = Newcase.find(params[:id])
  @newcase.update_attribute(:married, 'yes')
end

Add the route:

get '/newcase_yes_married`, to: 'newcase#yes_married'

You'd need to change new_path to newcase_yes_married_path (or whatever path rails routes returns in the terminal).

However a better solution would be to piggyback an update method to keep it RESTful.

def update
  @newcase = Newcase.find(params[:id])
  @newcase.update_attributes(newcase_params)
end
<%= link_to "Yes", [@newcase, { newcase: { married: 'yes' }}], method: 'patch' %>

Note: code not tested.

Upvotes: 1

Related Questions