Search code examples
htmlruby-on-railsformsrelationships

Create a form for accessing relationships in RoR 3


This is kind of evolution of my previous question (although I changed a lot, including model names so figured I should better create another thread).. and the nature of question changed as well..

Currently I am struggling to create a form for the function @dot2.link!(@dot)

The function works fine in console.

Here is the info from models / controllers (I tried to keep it minimal):

class User < ActiveRecord::Base
 has_many :dots, :dependent => :destroy
  ....
 end

Dot

class Dot < ActiveRecord::Base
  belongs_to :user
  has_many :linkages
   ...
  def link!(new_dot)
      linkages.create!(:end_id => new_dot.id)
         end
  ...
  end

Linkages:

class LinkagesController < ApplicationController
...
    def create
       @dot = current_user.dots.find(params[:linkages][:end_id])
       @dot2 = Dot.find(params[:id])
       @dot2.link!(@dot) 
    end

Linkages migration:

class CreateLinkages < ActiveRecord::Migration
     def self.up
    create_table :linkages do |t|
    t.integer :start_id
    t.integer :end_id
            t.timestamps
        end

add_index :linkages, :start_id
        add_index :linkages, :end_id
        add_index :linkages, [:start_id, :end_id], :unique => true
    end
...
    end

Now in console if I do

User.first.dots.first.link!(User.second.dots.second)

everything works fine.

How would I create a form for it (using just dot_id) as input??

Thanks!


Solution

  • Look up the collection_select form helper. It renders an association however you like, defaults to a Selectbox.