如何用虚拟属性更新模型的属性?

2024-04-18

我有一个名为UserPrice其具有属性:purchase_date(a date_select) 在其表中。使用我的表单,我可以一次创建多个 user_prices,但为了用户方便,我在我的表单中创建了一个虚拟属性UserPrice模型称为:all_dates这也是一个 date_select 字段,它的作用是替换:purchase_dates所以用户只需选择:all_dates日期字段。


问题与疑问

The :all_dates字段没有更新:purchase_date正在创建的 user_prices 字段。我需要做什么才能获得我的:all_dates字段来更新:purchase_date我的新领域UserPrices?

有人对如何执行此操作有任何提示吗?


参数

Parameters: 
"user_price"=> { 
"all_dates(2i)"=>"10", 
"all_dates(3i)"=>"27", 
"all_dates(1i)"=>"2011"
}, 
"user_prices"=>
{
"0"=>{"product_name"=>"Item1", "store"=>"Apple Store","price"=>"6"}, 
"1"=>{"product_name"=>"Item2", "store"=>"Apple Store", "price"=>"7"}
}, 
"commit"=>"Submit"}

Code

  class CreateUserPrices < ActiveRecord::Migration
    def self.up
       create_table :user_prices do |t|
          t.decimal :price
          t.integer :product_id
          t.date :purchase_date
          t.timestamps
        end
     end
  end

我拿出了:purchase_date字段,因此它不在 user_price 循环内部。

<%= form_tag create_multiple_user_prices_path, :method => :post do %>
 <%= date_select("user_price", "all_dates" )  %>
   <% @user_prices.each_with_index do |user_price, index| %>
      <%= fields_for "user_prices[#{index}]", user_price do |up| %>
          <%= render "user_price_fields", :f => up %>
      <% end %>
   <% end %>
<% end %>




class UserPrice < ActiveRecord::Base
  attr_accessible :price, :product_name, :purchase_date, :all_dates, :store
  attr_accessor :all_dates
  after_save :save_all_dates_to_user_prices
  composed_of :all_dates, :class_name => "DateTime",
    :mapping => %w(Time to_s),
    :constructor => Proc.new { |item| item },
    :converter => Proc.new { |item| item }

  def user_prices
    @user_prices = Array.new() { UserPrice.new }
  end

  protected

  def save_all_dates_to_user_prices 
     if !self.all_dates.nil?       
      self.user_prices.each {|up| up.purchase_date = self.all_dates if up.new_record?}
     end
  end


class UserPricesController < ApplicationController

 def new
    @user_prices = Array.new(5) { UserPrice.new }
 end

 def create_multiple
   @user_prices = params[:user_prices].values.collect { |up| UserPrice.new(up) }
   if @user_prices.all?(&:valid?)
     @user_prices.each(&:save!)
     redirect_to :back, :notice => "Successfully added prices."
   else
     redirect_to :back, :notice => "Error, please try again."
   end
end

这是一个尝试在模型中完成最好留给控制器处理的情况。您在这里要做的就是在创建时从不直接与模型关联的参数自动分配某个属性。但是您甚至没有将该额外参数传递给模型的任何地方 - 您正在从user_prices参数哈希的一部分,但是user_price子哈希没有在任何地方使用。无论如何,与模型相比,这是与视图和所采取的操作更密切相关的行为,因此将其保留在控制器中。

尝试这个:

  1. 扔掉虚拟属性,整体摆脱掉after_save回调的东西
  2. 扔掉user_prices模型中的方法
  3. 改变all_dates属性名称返回purchase_date以形式

那么你的参数哈希应该如下所示:

{"user_price"=> { 
  "purchase_date(2i)"=>"10", 
  "purchase_date(3i)"=>"27", 
  "purchase_date(1i)"=>"2011"
}, 
"user_prices"=>
{
  "0"=>{"product_name"=>"Item1", "store"=>"Apple Store","price"=>"6"}, 
  "1"=>{"product_name"=>"Item2", "store"=>"Apple Store", "price"=>"7"}
}}

剩下要做的就是合并单个user_price每个属性user_prices你的子哈希create_multiple行动。将该操作中的第一行替换为:

@user_prices = params[:user_prices].values.collect do |attributes| 
  UserPrice.new(attributes.merge(params[:user_price])) 
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何用虚拟属性更新模型的属性? 的相关文章

随机推荐

  • 如何在 Android 的服务类中实现 BroadcastReceiver?

    我需要在我创建的 Service 类中实现 BroadcastReceiver public class MyService extends Service 在本课程中 我必须使用线程 当用户按下按钮时睡眠来实现下载模拟MyActivity
  • 平台调用 F# 回调函数

    我在 Raspberry Pi 2 ARM 7 和单声道 上使用 F 我目前正在尝试使用用 C 编写的 WiringPi 库 我已经成功地使用 P Invoke 来使用一些函数 现在我尝试使用中断 参见http wiringpi com r
  • React.js:如何在单击时附加组件?

    我是 React 新手 我对一些基本的东西感到困惑 我需要在 DOM 渲染后 在单击事件上将组件附加到 DOM 我的初步尝试如下 但没有成功 但这是我想尝试的最好的事情 提前为将 jQuery 与 React 混合而道歉 ParentCom
  • 无法加载配置类

    我正在关注this http www tutorialspoint com spring spring java based configuration htm关于如何使用 Spring 的教程并根据提供的示例 我得到以下异常 Except
  • Yesod持久类型错误

    我正在 Yesod 应用程序中尝试持久化 我的模型文件包含 Job issuer MemberId addDate UTCTime lastDate UTCTime title Text description Text deriving
  • Xcode 5 中单元测试的使用

    我正在编写我的第一个更大的 iOS 项目 我想尽可能多地使用 Xcode 5 现在我想使用测试 但我以前从未这样做过 我的项目使用来Views和动态 TableViews 我怎样才能在代码中实现测试 使其有意义 请先观看 WWDC 13 会
  • 适合约 250,000 张图像的最佳 Web 文件夹结构

    我的网站将包含大约 200 000 张图像 每张图像将被存储 3 次 全尺寸 缩略图 更大缩略图 全尺寸图像约为 50Kb 至 500Kb 普通技术 VPS 上的 Linux Apache MySQL PHP 存储这些内容以便通过浏览器快速
  • 如何监视 JavaScript 中的递归函数

    Note 我已经看到这个问题以不同的方式提出并参考不同的测试工具 我认为清楚地描述问题和解决方案会很有用 我的测试是使用编写的诗乃间谍 https sinonjs org 为了可读性并将使用运行Jest https jestjs io en
  • 如何通过 TIdHTTP 下载大文件?

    我使用此代码下载小文件 Var ms TMemoryStream begin ms TMemoryStream Create Idhttp1 get http mydomain com myfile zip ms ms SaveToFile
  • 无法连接到 VS2012 中的 localDB –“建立与 SQL Server 的连接时发生网络相关或特定于实例的错误...”

    这很奇怪 因为我能够使用相同的连接字符串通过 SSMS 2008R2 连接到 localDB Data Source LocalDB v11 0 Integrated Security true Only C 代码无法连接 我尝试增加登录时
  • 创建流而无需从中创建物理文件

    我需要创建一个包含服务器上存在的文档的 zip 文件 我使用 Net Package 类来执行此操作 并创建一个新的 Package 即 zip 文件 我必须具有物理文件或流的路径 我试图不创建一个实际的 zip 文件 而是创建一个存在于内
  • makemessages 的 Unicode 问题 --all Django 1.6.2 Python 3.3

    升级项目Python 2 7 gt 3 3 1 and 姜戈1 4 gt 1 6 2 更新代码后我们的应用程序再次运行 in py3 翻译正在从 mo files 唯一的问题是我们的旧 po文件不能与 django admin py mak
  • 在 ASP.NET 5 中动态加载程序集

    我曾经有一些代码可以扫描bin我的应用程序的目录中包含尚未加载到 AppDomain 中并加载它们的程序集 它基本上看起来像 foreach var assemblyPath in Directory GetFiles path to bi
  • 根据字符串中多个单词的精确匹配转换新列

    我有一个数据框 df lt data frame Otherspp c suck SD BT SD RS RSS Dominantspp c OM OM RSS CH Commonspp c OM Rarespp c SD NP NP re
  • 什么是 print(f"...")

    我正在阅读一个 python 脚本 该脚本接受 XML 文件的输入并输出 XML 文件 但是 我不明白打印语法 有人可以解释一下吗f in print f does args parser parser args print f Input
  • 如何使用 Ruby CSV 转换器?

    假设您有以下文件 textfield datetimefield numfield foo 2008 07 01 17 50 55 004688 1 bar 2008 07 02 17 50 55 004688 2 读取 csv 的 Rub
  • 如何在 TCPDF 中设置下边距?

    我正在使用 TCPDF 生成 pdf 我可以使用设置左 上 右的边距SetMargins left top right 1 keepmargins false 但无法设置 pdf 页面底部的边距 任何人都可以帮助我在 TCPDF 中设置底部
  • Google Drive api 和服务帐户

    我为我的帐户创建了服务帐户 电子邮件受保护 cdn cgi l email protection 谷歌应用程序 和我的应用程序运行良好 然后我为我的个人帐户创建了服务帐户 电子邮件受保护 cdn cgi l email protection
  • 通过我们的应用程序使用“向朋友和家人汇款”功能

    我们的应用程序需要利用 向朋友和家人汇款 功能 现在我们可以使用 AdaptivePayments 执行个人支付 无需支付任何费用 如预期 但这种类型的交易似乎是购买交易 而不是 向家人和朋友汇款 交易 查看付款详细信息 而不是查看与 向朋
  • 如何用虚拟属性更新模型的属性?

    我有一个名为UserPrice其具有属性 purchase date a date select 在其表中 使用我的表单 我可以一次创建多个 user prices 但为了用户方便 我在我的表单中创建了一个虚拟属性UserPrice模型称为