我在这里研究过其他JSON渲染问题,但我没有发现任何想要以数组结尾的东西。我发现很多关于渲染为哈希的帖子,但它们没有帮助。
最近的尝试包括:
def create
params[:_json].each do |ip|
IpAddress.create(ip: ip)
end
ips = IpAddress.pluck(:ip)
ips.each do |ips|
ips.to_s
end
render json: ips
end
以及
def create
params[:_json].each do |ip|
IpAddress.create(ip: ip)
end
render json: IpAddress.all, methods: [:ip]
end
这两次尝试都返回整个数据库行数组。
感谢任何帮助。谢谢!
答案 0 :(得分:0)
这应该是一般的。 只需在创建数据库条目时构建阵列,然后将其返回。
def create
ips = params[:_json].inject([]) do |a, ip|
a << IpAddress.create!(ip: ip).ip
a
end
render json: {ips: ips}
end
答案 1 :(得分:0)
抱歉,我的def创建操作不是问题。它渲染得当,但问题是我的测试失败了,因为在创建之后,它正在点击索引操作以查看阵列是否已正确保存。所以,我添加了
def index
render json: IpAddress.pluck(:ip)
end
我的测试通过了。
感谢您的帮助。