gpt4 book ai didi

ruby-on-rails - ruby rails : compose attribute of model from virtual attributes

转载 作者:行者123 更新时间:2023-12-03 18:34:17 26 4
gpt4 key购买 nike

我有模型 Person 的属性 name

我想使用带有字段的 html 表单:first_namesurname:

<%= f.text_field first_name%>
<%= f.text_field surname%>

我想将这些虚拟属性组合成模型属性name

最好的方法是什么?

我尝试使用 composed_of , 但失败了...

class Person < ActiveRecord::Base
composed_of :name, :class_name => 'Name', :mapping => %w(name output_name)
end

class Name
attr_reader :output_name
def initialize(first_name, surname)
@output_name = first_name + surname
end
end

@person.attributes= {"name(1s)" => 'Alex', "name(2s)" => 'Bolduin' }
@person.name.should == 'Alex Bolduin'

expected: "Alex Bolduin",
got: #<Name:0x000000049d4c08 @output_name="Alex Bolduin"> (using ==)

我使用 Ruby on Rails 3,但我认为 Rails 3 和 Rails 2.3 的解决方案类似

最佳答案

你应该能够在模型中做一个假列做这样的事情:

class Person < ActiveRecord::Base
def name
"#{self.first_name} #{self.surname}"
end

def name=(fullname)
first,last = fullname.split(' ') # or some smarter way to split
self.first_name = first
self.surname = last
end
end

它应该可以像任何其他列一样访问,当您尝试设置 name 时,它只会调用 first_namesurname 的 setter 方法


如果你想反其道而行之,你仍然可以使用相同的技巧:

class Person < ActiveRecord::Base
def first_name
name.split(' ')[0]
end

def surname
name.split(' ')[1]
end

def first_name=(first)
name = [first, name.split(' ')[1]].join(' ')
end

def surname=(sname)
name = [name.split(' ')[0], sname].join(' ')
end

end

唯一可能不好的是字符串操作在每次读取时发生一次,在每次写入时发生两次。您也可以通过在 @person.save 之前添加类似这样的内容来创建/更新来捕获 Controller 中的内容:

@person.name = [first_name, surname].join(' ')

关于ruby-on-rails - ruby rails : compose attribute of model from virtual attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3338255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com