mercredi 26 octobre 2016

setting a variable before an if statement ruby

I am working using rails and I have a class from activerecord called Car. In the application that I am building,The application let's the user add a new car in one the pages or if not they can choose the one that it's already there.

I am having difficulties trying to come up with a solution, although both of them work it would only execute until some part of code because it's in an if/else statement.

ad_group_controllers.rb

if params[:ad_group][:file]
        @car = Car.create(year: params[:ad_group][:car][:year],model: params[:model],make_id: params[:make], trim: params[:trim])
        @car.update(file: params[:ad_group][:file])
        @ad_group.car = @car
    else
        @car = Car.find(params[:ad_group][:car][:id])
        @trim = params[:trim] == 'none' ? nil : params[:trim]
        @promotional_logo = params[:promotional_logo].blank? || params[:promotional_logo].downcase == 'none' || params[:promotional_logo] == '0' ? nil : PromotionalLogo.find(params[:promotional_logo])
        if (@promotional_logo && @ad_group.promotional_logo.nil?) || (@promotional_logo.nil? && @ad_group.promotional_logo)
            @ad_group.promotional_logo = @promotional_logo
            @ad_group.adjust_for_promotional_logo
        end
        @ad_group.update_attributes(make: @make, car: @car, trim: @trim, client: @client, rollover: params[:ad_group][:rollover], promotional_logo: @promotional_logo || nil)
        AdGroup.fields.each do |field|
            @ad_group[field] = params[:ad_group][field]
        end
    end
    @ad_group.ads.each do |ad|
        url = @ad_group.car.file.blank? ? nil : @ad_group.car.file.url
        car = @ad_group.car.file.blank? ? nil : @ad_group.car
        ad.images.find_by(name: 'car').update(url: url, car: car)

        url = @ad_group.promotional_logo.blank? ? nil : @ad_group.promotional_logo.file.url
        logo = @ad_group.promotional_logo.blank? ? nil : @ad_group.promotional_logo
        ad.images.find_by(name: "promotional_logo").update(url: url, promotional_logo: logo)

        ad.texts.find_by(name: "client_name").update(content: @client.name)

        if @ad_group.car.blank?
            car_name = ''
        else
            car_name = "#{@car.year} #{@make.name} #{@car.model}"
            car_name += " #{@car.trim}" unless params[:trim] == 'none' || params[:trim].blank?
        end
        ad.texts.find_by(name: "car_name").update(content: car_name)

Basically the if statement it's stating that if's there is a file in the adgroup paramaters create a car, and if not it should stay as

@car = Car.find(params[:ad_group][:car][:id])

the code below that has to execute for both cases. what is the best way to do this without repeating the code in the if and the else.

Aucun commentaire:

Enregistrer un commentaire