1

I have a simple database where users can create a task. I would like the index page to show which users created which task The relationship between task and user is 1 user to many tasks. The task has a user_id foreign key. Users can only create a task when they are logged in via Devise.

My create controller is as follows but I don't know how to record the foreign key for that task i.e. the user that created it.

def create
    @challenge = Challenge.new(challenge_params)

    respond_to do |format|
      if @challenge.save
        format.html { redirect_to users_path, notice: 'Challenge was successfully created.' }
        format.json { render :show, status: :created, location: @challenge }
      else
        format.html { render :new }
        format.json { render json: @challenge.errors, status: :unprocessable_entity }
      end
    end
  end
2
  • Can you show your method challenge_params Commented Jul 17, 2015 at 16:46
  • I think thats the problem. This was created by rails scaffold but I don't have this method- presumably this is the way to pass in the user_id but I don't know how to create a method to do this Commented Jul 17, 2015 at 16:57

1 Answer 1

2

Then you should this:

@challenge = Challenge.new(challenge_params.merge({user_id: current_user.id}))
Sign up to request clarification or add additional context in comments.

1 Comment

OK. it worked. Thanks. I suppose the learning point is that the params that are passed are also part of the INSERT TO statement. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.