Ruby on rails one to many association -
i new rails. have 1 many association. table1 few fields. 1 field title location, 1 title ccode. table2 how ever has 2 fields, first field location, , 2nd ccode. table hold location. in table1 when create object assign ccode , want corresponding location ccode table2. table2 has_many table1 , table1 belongs_to table2. want display location in index view in <table>
tag. think view code looks example had found , understand html enough. problem getting table2 object returns nil.
here model table1 looks like.
class table1 < activerecord::base belongs_to :table_2 require 'csv' def self.import(file) csv.foreach(file.path, headers: true, row_sep: :auto, col_sep: "\t") |row| table1.create! row.to_hash end end end
here model table2 looks like.
class table2 < activerecord::base self.table_name = 'table_2' self.primary_key = 'ccode' has_many :table1 end
here table1controller looks like
class financialscontroller < applicationcontroller def index @financials = financial.all end def create @financial_loc_ccode = financiallocccode.create(location_code: params[:location_cd], ccode: @financials.ccode) end end
i not have table2 controller, done in table1 controller, assume because when started project there table created table2.
like said before new rails , still learning connections between models , controllers, , how manipulate data , has has displaying in html.
any appreciated.
i'll focus on table2 being nil.
it's nil because you're not creating it.
go terminal , type rails g controller table2 create
open file , inside of empty create
method create new table2 object.
you can many ways, important thing remember when have associations need define association when you're creating it.
i'll give example:
let's have user model
user model
class user < activerecord::base has_many :posts end
now let's have post model , want user able create many posts.
post model
class post < activerecord::base belongs_to :user end
now important part utilize table2 controller
when create new post, has belongs_to
user, therefor this
post controller
class postscontroller < applicationcontroller def create #store object has many posts variable @user = current_user #the important part, when create post need @post = @user.posts.create(post_params) end end
whats happening here is, rails creating new post under ownership of @user
. how establish relationship association.
i hope helped clear relationships little bit, if not here docs might too.
Comments
Post a Comment