stewart715
stewart715

Reputation: 5637

rails using has_many and belongs_to

Alright, I'm going to try to explain this as best as possible:

I have two models

employer.rb

class Employer < ActiveRecord::Base

    has_many :listings

end

listing.rb

class Listing < ActiveRecord::Base

    belongs_to :employer

end

Employers login through the employers_controller and listings are created through listings_controller

I'm having trouble getting the id from the employer table being inserted into the employer_id column in each individual created listing. I hope this makes sense. If anyone has any advice, it would be much appreciated. I have a feeling this is because I'm doing this outside of the employer_controller, but not sure.

Thanks!

Upvotes: 1

Views: 380

Answers (2)

Sohan
Sohan

Reputation: 3805

I think you have the employer id in your session, since they need to login to create the listing. I won't use the param from the view, then its easy for one employer to create a listing as if it was created by another employer, just by changing the id value in your hidden field. Here's what is possibly a better approach:

@employer = Employer.find(current_user.id)
@employer.Listing.new(params[:listing] 

Upvotes: 0

naren
naren

Reputation: 937

1) If you are not dealing as nested resource then

When you render the new action of Listing controller, you know for which employer (@employer) you want to create the listing.

So render a hidden field for employer_id using a hidden_field or hidden_field_tag

hidden_field_tag 'employer_id', @employer.id()

2) If you are dealing as nested resource and your route looks something like /employers/:employer_id/listings/new / (Get) && /employers/:employer_id/listings

Then in create action

@employer = Employer.find(params[:employer_id])
@employer.Listing.new(params[:listing] 

Upvotes: 2

Related Questions