Rails - add validation errors from controller -


booking model belongs_to discountcode. booking form has string input discount_code, turned discountcode in controller:

updated_params = booking_params if updated_params[:discount_code]   updated_params[:discount_code] = discountcode.find_by code: updated_params[:discount_code] end @booking = booking.new(updated_params) 

so right if code entered not exist, updated_params[:discount_code] nil, same if no discount code entered. rather add error @booking.discount_code in if statement, i'm in controller, possible?

the solution sort of thing simple, standard, agnostic , scaffoldy @booking in controller, @booking = booking.new(params[:booking]) or @booking.update_attributes(params[:booking]). try keep controller methods standard possible , push logic models , data views.

so, leads on passing discount code through via booking setter method. if don't have setter method rails, need add it. let's assume there's association "has_one :discount_code" in booking. can write setter method make association code, , validate so.

(note it's confusing have field called "code" in class called "discountcode" - you're going writing @discount_code.code begs question "is 'code' string of letters , numbers '12dafj1213', or 'code' activerecord object loaded out of database?". i'd recommend either renaming class "discount" (so @discount.code) or renaming "code" field "token" (so @discount_code.token). haven't addressed issue in solution, i've stuck naming, code looks quite confusing "code_code" stuff.

class booking   attr_accessor :discount_code_code   has_one :discount_code    before_validation :set_discount_code_from_discount_code_code   validate :check_we_have_discount_code_if_we_have_discount_code_code    def set_discount_code_from_discount_code_code     unless self.discount_code_code.blank?       self.discount_code = discountcode.find_by_code(self.discount_code_code)     end   end    def check_we_have_discount_code_if_we_have_discount_code_code     if !self.discount_code_code.blank? && !self.discount_code       self.errors.add(:discount_code, "is not valid discount code")     end       end end 

your form (which i'd expect form_for @booking) should include this

<%= f.text_field :discount_code_code %> 

which come through in params

params = {:booking => {:discount_code_code => "12dafj1213"}} 

and in controller should say

@booking = booking.new(params[:booking]) if @booking.save   ...etc 

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 -