Jonathan Evans
Jonathan Evans

Reputation: 1034

Adding a button to a view for updating a model in rails

I have two resources, A and B with a many to many relationship between them. When pressing a button on A's show view I wish to establish the relationship between the A object and a B object which I also have access to from the view.

How can you do this in rails3?

Edit: A relevant snippet of the relationship. Everything else is standard generated using rails generate scaffold

class Course < ActiveRecord::Base
  ...
  has_many :course_auth_users
  has_many :students, :through => :course_auth_users, :source => :user
  ...
end


class User < ActiveRecord::Base
  ...
  has_many :course_auth_users
  has_many :enrolled_on_courses, :through => :course_auth_users, :source => :course
  ...
end

Upvotes: 0

Views: 76

Answers (1)

Leo Correa
Leo Correa

Reputation: 19789

I'm assuming you have a model like so

class CourseAuthUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :course
end

I'm also assuming you mean that object A and B have already been created. Your Users controller should have an action that adds a course to its list like so:

class UsersController < ApplicationController
  def enroll_course
    @student = User.find(params[:id])
    @course = Course.find(params[:course])  

    @student.enrolled_on_courses << @course

    @student.save!
  end
end

Notice the controller part assumes you are passing a user_id and a course in the request parameters.

Let me know if this helps. I wasn't too sure what your requirements were.

Upvotes: 2

Related Questions