Rails - 提交已存在的嵌套值

时间:2011-04-16 23:21:03

标签: ruby-on-rails ruby-on-rails-3

我有一个模型,Tran,它具有User模型的外键。在创建Tran(事务)的视图中,我有一个下拉列表,允许用户选择启动事务的用户。当我发布此事务时,使用正确的用户ID设置记录:

然后,在我的Trans模型中,我添加了“belongs_to”,据我所知,我应该为外键执行此操作:

class Tran < ActiveRecord::Base
    belongs_to :buying_user, :class_name => 'User'

现在,当我的客户端在帖子中传递了params时,我的Tran.new因为我传递了一个userID而不是一个完整的记录而崩溃了。是

#trans_controller.rb
def create
    @title = "Create Transaction"
        #bombs on this call
    @tran = Tran.new(params[:tran])

我该怎么办呢?

按要求更新: tran.rb

class Tran < ActiveRecord::Base
    has_many :transaction_users, :dependent => :destroy, :class_name => 'TransactionUser'
    belongs_to :submitting_user, :class_name => 'User'
    belongs_to :buying_user, :class_name => 'User'

    accepts_nested_attributes_for :transaction_users, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

    validates :description, :presence => true,
                            :length => {:maximum => 100 }
    validates :total,       :presence => true
    validates_numericality_of :total, :greater_than => 0

    validates :submitting_user,         :presence => true           
    validates :buying_user,             :presence => true   

    validates_associated :transaction_users

end

user.rb

class User < ActiveRecord::Base
    has_many :trans
    attr_accessor :password
    attr_accessible :firstname, :lastname, :email, :password, :password_confirmation

    email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i


    validates :firstname, :presence => true,
                            :length => {:maximum => 50 }
    validates :lastname, :presence => true,
                            :length => {:maximum => 50 }
    validates :email, :presence => true,
                            :format => {:with => email_regex },
                            :uniqueness => { :case_sensitive => false }

    validates :password, :presence => true,
                            :confirmation => true,
                            :length => { :within => 6..40 }

    # Register callback to before save so that we can call extra code like password encryption                      
    before_save :encrypt_password

    # Class methods
    def self.authenticate(email, submitted_password)
        user = find_by_email(email)
        return nil if user.nil?
        return user if user.has_password?(submitted_password)
    end

    def self.authenticate_with_salt(id, cookie_salt)
        user = find_by_id(id)
        (user && user.salt == cookie_salt) ? user : nil
    end

    # Public methods

    def has_password?(submitted_password)
        self.encrypted_password == encrypt(submitted_password)
    end

    def full_name 
        "#{self.lastname}, #{self.firstname}"
    end

    def self.active_users
        # TODO
        #User.find_
        User.all

    end


    private

        def encrypt_password
            self.salt = make_salt if new_record?
            self.encrypted_password = encrypt(password)
        end

        def encrypt (string)
            secure_hash("#{salt}--#{string}")
        end

        def make_salt
            secure_hash("#{Time.now.utc}--#{password}")
        end

        def secure_hash(string)
            Digest::SHA2.hexdigest(string)
        end
end

报名参数提交:

{"commit"=>"Submit",
 "tran"=>{"total"=>"100",
 "submitting_user"=>"1",
 "description"=>"Description"},
 "authenticity_token"=>"88qI+iqF92fo/M9rPfMs1CLpEXqFLGQXfj0c9krXXac=",
 "utf8"=>"✓",
 "user"=>"1"}

错误:

User(#70040336455300) expected, got String(#70040382612480)

控制器的开头:

def create
    @title = "Create Transaction"
    @tran = Tran.new(params[:tran])

它在Tran.new线上崩溃了。非常感谢!

2 个答案:

答案 0 :(得分:1)

通常,用户模型会has_many :transactions, :class_name => Tran 然后你会这样做......

@user.transaction_create(params[:tran])
or
@user.build

它取决于在params [:tran]中实际传递的参数,但是想法是has_many方面创建了belongs_to。

答案 1 :(得分:1)

我明白了!问题一直是我的Trans表上链接到我的Users表的我的db列名是submitting_user而不是submitting_user_id。然后,当我将belongs_to关联添加到submitting_user rails时,混淆并使该字段成为User,而不是整数。