Check if Form input was empty

时间:2015-07-28 16:09:39

标签: ruby-on-rails ruby ruby-on-rails-4

I have the following parameters

def note_params
    params.require(:note).permit(
      :content
    )
  end

Now i am trying to check of the content was empty for :content i am passing this to a service object

def add_note_to_plan
    unless @note_params.content.empty?
      puts "======================================================"
      note = Note.new(
        note_params.merge(
          plan: @plan,
          user: @current_user
        )
      )

      note.save
    end
    puts "=================== outside ==================================="
  end

Service Object

    class PlanCreator
      def initialize(current_user, venue_params, plan_params, note_params)
        @current_user = current_user
        @venue_params = venue_params
        @plan_params = plan_params
        @note_params = note_params
      end

      attr_reader :venue, :plan

      def create
        @venue = new_or_existing_venue
        @plan = new_or_existing_plan

        save_venue && save_plan && add_current_user_to_plan && add_note_to_plan
      end

      def errors
        {
          venue: venue_errors,
          plan: plan_errors,
          note: note_errors
        }
      end

      private

      attr_reader :current_user, :venue_params, :plan_params, :note_params

    ..... Removed all the unnecessary methods


      def add_note_to_plan
        unless @note_params.content.empty?
          puts "======================================================"
          note = Note.new(
            note_params.merge(
              plan: @plan,
              user: @current_user
            )
          )

          note.save
        end
        puts "=================== outside ==================================="
      end


end

Error:

NoMethodError - undefined method `content' for {"content"=>""}:ActionController::Parameters:

1 个答案:

答案 0 :(得分:3)

Change this:

unless @note_params.content.empty?

To this:

unless @note_params[:content].empty?

ActionController's params returns a hash of parameters.