Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have Rails form with textarea. User puts text spltted by comma, then submit to server, where data validates, splits to array and writes to postgres database.

But there is null array in callback before_validation. Here's it:

class UsersController < ApplicationController

def update
  @user = User.find(params[:id])
  if @user.update(user_params)
    # show profile
  end
end

private
  def user_params
    params.require(:user).permit(
      :nickname,
      :password,
      {tags:[]})
  end

and

class User < ActiveRecord::Base

  before_validation :tags_must_be_list

  def tags_must_be_list
    p tags ####### here is tags is empty [], but need to be text
    errors.add(:tags, "is not list")
  end

What's wrong?

share|improve this question
    
can you paste the development logs –  NitinJ Dec 25 '13 at 5:45

1 Answer 1

up vote 0 down vote accepted

You're saying that the tags are supposed to be an array:

params.require(:user).permit(
  :nickname,
  :password,
  {tags:[]}) # <--------- `:tags` is supposed to be an array

but the tags are coming in as a single CSV string rather than an array so presumably they're being filtered out because a string is not an array.

There are various options:

  1. Use some JavaScript to split the string into individual tags on the client and rewrite the form (using JavaScript) to submit individual tags[] parameters rather than a single tags string.
  2. Say permit(:nickname, :password, :tags) and then split the tags into an array in the controller:

    user = user_params
    user[:tags] = user.delete(:tags).to_s.split(/\s*,\s*/)
    @user.update(user)
    
  3. Provide your own User#tags= method to split the string before storing the tags (or maybe a before_validation hook to arrayify the tags if they're not an array already). You'd need the permit change from 2 here as well and I'm not sure what AR would do to your string before your before_validation hook ran, the tags= override should work sensibly though.

I'd probably go with 2 but many people would consider that heresy and bloat the model with 3 instead.

share|improve this answer
    
Thank you, second method seems to work. But what about third? it's looks logical, but tags param is empty in before_validation hook –  br. Dec 25 '13 at 8:37
    
You'd have to combine the permit change in 2 with the stuff in 3. I'm not sure how we'll that would work though, AR might try to arrayify the string behind your back and make a mess if things. –  mu is too short Dec 25 '13 at 17:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.