[英]Rails: Model methods issue with saving
I have a text_area
named answer_choices
in my form that's used for inputting answers (separated by a line break): 我的表单中有一个名为
answer_choices
的text_area
,用于输入答案(以换行符分隔):
Some answer
Another answer
Yet another
So when a users submits the form, I parse answer_choices
out into individual answers for input into the database using answer_choices.split(/\\r\\n/)
因此,当用户提交表单时,我解析
answer_choices
使用为三个独立的答案输入到数据库中answer_choices.split(/\\r\\n/)
Then, when they edit the form, I reassemble those individual answers using this method: 然后,当他们编辑表单时,我将使用以下方法重新组合这些单独的答案:
I have the following method in my Question
model: 我的
Question
模型中有以下方法:
def answer_choices
string = ''
answers.each do |answer|
string += "#{answer.text.to_s}\n"
end
string.strip
end
That lets me just do <%= f.text_area :answer_choices %>
in my view and I get the answers separated by line breaks. 这样一来,我就可以在视图中执行
<%= f.text_area :answer_choices %>
,并且得到的答案由换行符分隔。 Great. 大。
The problem is that when I submit the form again (to update the records), that little answer_choices.split(/\\r\\n/)
bit seems to be calling that custom method instead of taking any new data from the form field and thus just re-adds the same data from before. 问题是当我再次提交表单(以更新记录)时,那个小小的
answer_choices.split(/\\r\\n/)
位似乎正在调用该自定义方法,而不是从表单字段中获取任何新数据,因此只需重新添加之前的相同数据即可。
So how can I have my custom method for the form output? 那么,如何为表单输出提供自定义方法?
为了避免调用自定义方法,应使用属性哈希:
self.attributes['answer_choices'].split(/\r\n/)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.