Hello, i want to know if i am relationing fine, because i am having
problems,i have 2 models, one for members and other to relate some
members to this:
class Member < ActiveRecord::Base
has_many :matrix, :foreign_key=>:parent
end
class Matrix < ActiveRecord::Base
set_table_name :matrix
set_primary_key :userid
belongs_to :member, :foreign_key=>:userid
acts_as_tree :foreign_key=>:parent
end
when i try to save a new member it says: undefined method `userid=’ for
Matrix:Class and i think is because he wants to do find() first, but i
dont want it, because i am saving a new.
Well the problem is, that the table schema is thus, because in some case
i would rather use the rails convention an use member_id, in case of
userid, but i have to work with the actual table.
about foreign keys: in the has_many, you define parent as the foreign
key, in the belongs_to, you define userid as foreign key. but it has
to be the same on both sides, otherwise it’s no proper relation,
legacy Database or not.
You tell the Member model that is has many Matrix’ associated through
the parent column in the matrix table, but you tell the Matric Model
that it belongs to a Member associated by the userid column in the
matrix table … it should say “parent” here to, because the table on
the has_many side doesn’t have a foreign key, only the belongs_ to
side
You’ve defined userid as the primary key, which makes it accessable as
id (ie @matrix.id) rather than userid. The problem here, though, is
manifold:
Rails expects your database to be sane, which includes an id column
that is a unique auto-incrementing integer.
Using it as a foreign key means that you’ll have to set the primary
key of the record, which is a huge no-no in both rails and database
design and violates the auto-incrementing requirement.
Using is as a foreign key also implies that two records could share
the same foreign key, and therefore the same primary key, which
violates the unique requirement.
Rails can work with most legacy databases provided that they’re
relatively sane. Using a primary key as a foreign key is most
definitely insane and I doubt you’d make that table work properly with
or without rails.
def create @member = Member.new(params[:member]) @new_matrix = Matrix.new @new_matrix.parent = params[:member] <<<<— here is my problem
respond_to do |format|
if @member.save @new_matrix.userid = @member.id @new_matrix.save
…
end
end
how can i access to the params[:parent]??, because tis param is inside
the params[:member]