RubyonRails-JS输入令牌,验证失败时会出现问题



我有一个公司模型,它可以有很多标签。它运行良好,但有一次不起作用。有时公司模型验证失败。在:render=>"edit"之后,它不会在视图中显示标记。我怀疑数据预处理程序没有正确获取数据。我还希望在解决验证时保留标签。

我从这里得到了这个想法:http://railscasts.com/episodes/167-more-on-virtual-attributes

我使用输入令牌控制:http://loopj.com/jquery-tokeninput/

这是我在公司模型中关于标签的内容:

before_save :save_tag_tokens
attr_writer :tag_tokens
attr_accessible :tag_tokens
def tag_tokens
@tag_tokens || tags.to_json(:only => [:id, :name])
end
def save_tag_tokens
if @tag_tokens
@tag_tokens.gsub!(/CREATE_(.+?)_END/) do
Tag.create!(:name => $1.strip.downcase).id
end
self.tag_ids = @tag_tokens.split(",")
end
end

以下是视图中的代码:

<div class="input text no-border">
<% Tag.include_root_in_json = false %>
<%= company_form.label :tag_tokens, t('form.account.company.edit.company_tags_html')%>
<%= company_form.text_field :tag_tokens, :id => 'company_tag_tokens', "data-pre" => @company.tag_tokens%>
<p class="tip"><%= t('form.account.company.edit.tag_tip') %></p>
</div>

编辑:

好的,我知道上面的代码有什么问题了。

当我加载编辑页面数据时,预包含以下内容:data-pre="[{&quot;id&quot;:1704,&quot;name&quot;:&quot;dump truck&quot;}]"。当我提交带有验证错误的表单时,数据预包含:data-pre="1704"

如果我把代码改成这个:

def tag_tokens
tags.to_json(:only => [:id, :name])
end

尚未保存到公司模型中的新标记将被删除,因为它们每次都会从DB中读取。如何在表单转换之间保留输入的数据?

好吧,我已经写了一个解决方案,它可能不是最好的,但它对我有用!它将输入的令牌值解析为JSON格式(当验证失败时),该格式在加载页面时使用。在页面加载下,它只从DB加载标签。

def tag_tokens
if @tag_tokens
#if there is user info, parse it to json format. create an array
array = @tag_tokens.split(",")
tokens_json = []
#loop through each tag and check if it's new or existing
array.each do |tag|
if tag.to_s.match(/^CREATE_/)
#if new generate json part like this:
tag.gsub!(/CREATE_(.+?)_END/) do
tokens_json << "{"id":"CREATE_#{$1.strip.downcase}_END","name":"Add: #{$1.strip.downcase}"}"
end
else
#if tag is already in db, generate json part like this:
tokens_json << "{"id":#{tag},"name":"#{Tag.find_by_id(tag).name}"}"
end
end
#encapsulate the value for token input with [] and add all tags from array
"[#{tokens_json.to_sentence(:last_word_connector  => ',', :words_connector => ',', :two_words_connector => ',')}]"
else
#if there is no user input already load from DB
tags.to_json(:only => [:id, :name])
end
end

最新更新