开发者

Rails - Submitting Nested Values That Already Exist

I have a model, Tran that has a foreign key to the User model. In the view for creation a Tran (transaction), I have a dropdown that allows the user to select the User that started the transaction. When I post this transaction, the record is set with the correct user ID:

Then, in my Trans model I added "belongs_to", as I understand I should do this for foreign keys:

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

Now, when my client passes up the params in the post, my Tran.new craps out because I am passing up a userID and not a full record. Is the

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

How am I supposed to handle this?

Update as requested: 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_p开发者_运维百科assword?(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

params hash on submit:

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

error:

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

beginning of controller:

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

It crashes on the Tran.new line. Thanks so much!


Typically the User model would have has_many :transactions, :class_name => Tran Then you would do this...

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

it depends on what parameters are actually passed in params[:tran], but the idea is that the has_many side does the creating of the belongs_to.


I figured it out! The problem the whole time was that my db column name on my Trans table that linked to my Users table was submitting_user instead of submitting_user_id. Then, when I added the belongs_to association to submitting_user rails got confused and made that field a User, instead of an integer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜