问题描述:

I collect tags in a nice javascript UI widget. It then takes all the tags and passes them to the server as tag1,tag2,tag3,etc in one text_field input. The server receives them:

params[:event][:tags] = params[:event][:tags].split(',') # convert to array

@event = Event.find(params[:id])

Is there a better way to convert the string to the array? It seems like a code smell. I have to put this both in update and in the new actions of the controller.

网友答案:

you could do this in the model:

I have seldom experience on mongoid. The following would work in active record (the only difference is the write_attribute part)

class Event
  def tags=(value_from_form)
    value_from_form = "" unless value_from_form.respond_to(:split)

    write_attribute(:tags, value_from_form.split(','))
  end
end

On the other hand, for consistency, you may want to do the following:

class Event
  def tags_for_form=(value_from_form)
    value_from_form = "" unless value_from_form.respond_to(:split)

    self.tags = value_from_form.split(',')
  end

  def tags_for_form
    self.tags
  end

  # no need to change tags and tags= methods. and tags and tags= methods would return an array and accept an array respectively
end

In the first case (directly overwriting the tags= method), tags= accepts a string but tags returns an array.

In the second case, tags_for_form= and tags_for_form accepts and returns string, while tags= and tags accepts and returns array.

网友答案:

I just create another model attribute that wraps the tags attribute like so:

class Event
  def tags_list=(tags_string)
    self.tags = tags_string.split(',').map(&:strip)
  end

  def tags_list
    self.tags.join(',')
  end

end

In your form, just read/write the tags_list attribute which will always accept, or return a preformated string. (The .map(:strip) part simply removes spaces on the ends in case the tags get entered with spaces: tag1, tag2, tag3.

网友答案:

PeterWong's answer misses the '?' from the respond_to() method;

  class Event
    def tags=(value_from_form)
      value_from_form = "" unless value_from_form.respond_to?(:split)

      write_attribute(:tags, value_from_form.split(','))
    end
  end
相关阅读:
Top