Polymorphism and forms in Ruby on Rails - ruby-on-rails

I've been full of questions lately, but thanks to this awesome community, I'm learning a ton.
I got all the help I needed with polymorphic associations earlier and now I have a question about tackling forms with polymorphic models. For instance I have Phoneable and User, so when I create my form to register a user, I want to be able to assign a few phone numbers to the user (ie: cell, work, home).
class User < ActiveRecord::Base
has_many :phones, :as => :phoneable
end
class Phone < ActiveRecord::Base
belongs_to :phoneable, :polymorphic => true
end
class CreateUsers < ActiveRecord::Migration
t.column :name, :string
t.references :phoneable, :polymorphic => true
end
class CreatePhones < ActiveRecord::Migration
t.column :area_code, :integer
t.column :number, :integer
t.column :type, :string
t.references :phoneable, :polymorphic => true
end
Now when I create my form, I'm getting confused. Normally I would do the following:
- form_for :user, :html => {:multipart => true} do |form|
%fieldset
%label{:for => "name"} Name:
= form.text_field :name
##now how do I go about adding a phone number?
##typically I'd do this:
##%label{:for => "phone"} Phone:
##= form.text_field :phone
Using polymorphism, would I just approach the same way, but use fields_for?
- user_form.fields_for :phone do |phone| %>
%label{for => "area_code"} Area Code:
= phone.text_field :area_code
%label{for => "number"} Number:
= phone.text_field :number
Is this the correct approach in this instance?

Before we go further, I did notice one issue - you do not need the t.references with the has_many side of the association. So you do not need it in the create_user model. What that does is it creates the phonable_id and the phoneable_type columns, you only need that in the polymorphic model.
You are heading down the correct path with the fields_for approach. But in order to get that working, you need to tell the model how to handle those fields. You do that with the accepts_nested_attributes_for class method.
class User < ActiveRecord::Base
has_many :phones, :as => :phoneable
accepts_nested_attributes_for :phones
end
and one minor thing, you will need to have the fields_for point to the exact name of the association
- form_for #user do |user_form|
- user_form.fields_for :phones do |phone|
Instead of
- form_for #user do |user_form|
- user_form.fields_for :phone do |phone|
and make sure you remove your stray %> erb tag :)
More on accepts_nested_attributes_for: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
I hope this helps!

Related

Rails Active Admin when I create my form it only displays the last field. Permit params wont accept :page field

I am having 2 problems.
1) formtastic will only show the last input field instead of all of them. In this case it will only display:
r.input :sort_order
2) I had to do some wierd wrap f.inputs around each field to get it to show up which i believe is the wrong way. But when i submit the form it says Unpermitted parameters: page. When I did clearly define page I dont know how else to get permit params accept this.
Here is my model
class Fact < ActiveRecord::Base
has_one :page, as: :pageable, dependent: :destroy
accepts_nested_attributes_for :page
end
The other model:
class Page < ActiveRecord::Base
belongs_to :pageable, polymorphic: true
end
My active admin:
ActiveAdmin.register Fact do
permit_params :id, page_attributes: [:type, :name, :description :sort_order ]
form do |f|
f.inputs "My Page", for: [:page, f.object.page || Page.new] do |r|
r.input :name
r.input :description
r.input :sort_order
end
end
end

Add objects with specific category to join table and then display on page

I'm building a RoR app where Users can click book categories to add lists of books to their profile. I'm a bit new to this stuff, and I am currently a little stuck as to where to go next.
Models:
User (from Devise)
Book
Book_List (join table)
I have a few thousand books with various categories. Upon clicking a category, I want the books of that category to be added to the User's profile page.
This is what I have so far:
book.rb
class Book < ActiveRecord::Base
has_many :book_lists
has_many :users, :through => :book_lists
end
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :book_lists
has_many :books, :through => :book_lists
end
book_list.rb
class BookList < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
devise_create_users.rb Migration
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
# i only included relevant to the question stuff here.
# Standard Devise stuff taken out.
t.integer :user_id
book Migration
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.string :category
t.string :title
t.integer :book_id
t.timestamps
end
end
end
book_list Migration
class CreateBookLists < ActiveRecord::Migration
def change
create_table :book_lists do |t|
t.timestamps
end
end
end
book_list_controller.rb
class BookListController < ApplicationController
def save_book
#saved_book = BookList.new(params[:saved_book]
#saved_book.user = current_user
#saved_book.save
end
end
book list view
<%= form_for BookList.new, :url => "/books/save_book" do |f| %>
<%= f.hidden_field :book_id, :value => #book_id %>
<%= f.submit "Save Books" %>
<% end %>
What should I be adding to get the books to save to the User's profile page based on book category?
Sorry if the above code is nonsensical in any way. I pieced it together from various forums.
EDIT:
CodeApp::Application.routes.draw do
devise_for :users, path_names: {sign_in: 'login', sign_out: 'logout'}
get "profile", to: "profile#show"
resources :books
root "books#welcome"
get "search", to: "search#index"
get "about", to: "books#about"
get "books", to: "books#index"
post "save_book", to: "book_list#save_book"
This code
<%= form_for BookList.new, :url => "/books/save_book" do |f| %>
should be
<%= form_for #saved_book, :url => "/books/save_book" do |f| %>

Creating a Rails 3 HABTM with Active Admin throws a 'Can't mass-assign protected attributes:' error

I am a rails noob so the below is probably down to lack of understanding however I have been looking/reading all day and cannot seem to find the solution.
I have two models - project and technology :
Project :
class Project < ActiveRecord::Base
attr_accessible description, :name
has_and_belongs_to_many :technologies, :join_table => :projects_technologies
end
Technology :
class Technology < ActiveRecord::Base
attr_accessible :abbr, :description, :name
has_and_belongs_to_many :projects, :join_table => :projects_technologies
end
My Create_Projects_Technologies migration was as follows :
class CreateProjectsTechnologies < ActiveRecord::Migration
def self.up
create_table :projects_technologies, :id => false do |t|
t.references :project
t.references :technology
end
add_index :projects_technologies, [:project_id, :technology_id]
add_index :projects_technologies, [:technology_id, :project_id]
end
def self.down
drop_table :projects_technologies
end
end
I am then using Active Admin to create and edit Project models using the following form :
ActiveAdmin.register Project do
form do |f|
f.inputs "Project attributes" do
f.input :name
f.input :description
f.input :technologies, as: :check_boxes
end
f.buttons
end
end
This correctly shows all my technologies as check boxes however as soon as I submit the form I hit the following error which I have not been able to overcome :
ActiveModel::MassAssignmentSecurity::Error in Admin::ProjectsController#update
Can't mass-assign protected attributes: technology_ids
All help is very much appreciate :D
Simple add technology_ids to Project attr_accessible
attr_accessible :client, :description, :name, :technology_ids

Creating a dynamic collection select rails 3.1

I have gone through N number of solutions for creating a dynamic dropdown in rails but nothing seems to work.
I have a typical state and city model and I do not want to use carmen.
Here is my model :-
Market.rb
class Market < ActiveRecord::Base
attr_accessible :state, :cities_attributes
has_and_belongs_to_many :users
has_many :cities, :dependent => :destroy
accepts_nested_attributes_for :cities
validates :state, :presence => true, :uniqueness => true
end
City.rb
class City < ActiveRecord::Base
attr_accessible :city
belongs_to :market
has_and_belongs_to_many :users
end
in devise/registrations/new (I want the user to select the state and city at the time of signup itself)
%li
=f.collection_select :city, Market.all,:id, :state, html_options = { :class => "custom_textarea"}
%li
=render "devise/registrations/cities", :f => f
_cities.html.haml partial
-unless cities.blank?
=f.collection_select( :city, #cities, :id, :cities)
registrations_controller.rb
def update_city_select
#cities = City.where(:country_id => params[:id])
render :partial => "cities", :locals => {:cities => #cities}
end
I want the city list to change once the user selects a state and be populated with relevant cities.
How can I achieve this?
You must use ajax for this in your view which contains the state dropdown:
$("#stateDropdown").change(function(){
$.get("controller/update_city_select.html?id="+$("#stateDropdown").val(),
function(data){ $("#cityDropdownDiv").html(data); } );
});
This calls your action, and substitutes the content of your div to the new dropdown for cities.
To your partial:
#cityDropdownDiv
-unless #cities.blank?
= collection_select( :market, :city, #cities, :id, :cities)
With this, you don't need to add the :f => f parameter when rendering the partial.
You should add an id (I am assuming "stateDropdown") to your dropdown in the html_option part.
One more tutorial which was really helpfull and I guess will help anyone looking to implement dependent dropdown is http://www.petermac.com/rails-3-jquery-and-multi-select-dependencies/

Application design of controller (Rails 3)

This is hard to explain, but I will do my best:
I am building a system where user's can take courses. Courses are made up of steps, that must be taken in order. In the system there are 6 step types (Download, Presentation, Video, Text, Quiz, and Survey)
The way a user accesses a STEP currently is:
http://example.com/courses/2/course_steps/1
As you can tell course_steps are nested under courses.
Below is the show method in course steps:
def show
render "show_#{#course_step.step.step_type.name.downcase}"
end
As you can tell it basically picks a view to show_[TYPE] (quiz, survey, text..etc)
This works fine for simple steps such as a text, video, or download, but for complicated steps such as a quiz, this model does not work well for the following reasons:
How do I validate a form for a quiz or survey as I would be using a different controller (QuizAttemptsController).
It seems to break the REST principal as a quiz, survey..etc should be treated separately. (I know they are step types, but they can have their own actions and validations)
Step Model
class Step < ActiveRecord::Base
belongs_to :step_type
belongs_to :client
has_one :step_quiz, :dependent => :destroy
has_one :step_survey, :dependent => :destroy
has_one :step_text, :dependent => :destroy
has_one :step_download, :dependent => :destroy
has_one :step_video, :dependent => :destroy
has_one :step_presentation, :dependent => :destroy
has_many :course_steps, :dependent => :destroy
has_many :courses, :through => :course_steps
has_many :patient_course_steps, :dependent => :destroy
attr_accessible :step_type_id, :client_id, :title, :subtitle, :summary
validates :title, :presence=>true
validates :summary, :presence=>true
def getSpecificStepObject()
case self.step_type.name.downcase
when "text"
return StepText.find_by_step_id(self.id)
when "quiz"
return StepQuiz.find_by_step_id(self.id)
when "survey"
return StepSurvey.find_by_step_id(self.id)
when "download"
return StepDownload.find_by_step_id(self.id)
when "video"
return StepVideo.find_by_step_id(self.id)
when "presentation"
return StepPresentation.find_by_step_id(self.id)
end
end
end
Step Quiz Model:
class StepQuiz < ActiveRecord::Base
belongs_to :step, :dependent => :destroy
has_many :step_quiz_questions, :dependent => :destroy
has_many :quiz_attempts, :dependent => :destroy
accepts_nested_attributes_for :step
accepts_nested_attributes_for :step_quiz_questions, :allow_destroy => true
attr_accessible :step_id, :instructions, :step_attributes, :step_quiz_questions_attributes
validates :instructions, :presence=>true
end
CourseStep Model
class CourseStep < ActiveRecord::Base
belongs_to :step
belongs_to :course
validates_uniqueness_of :step_id, :scope => :course_id
def next_step()
Course.find(self.course.id).course_steps.order(:position).where("position >= ?", self.position).limit(1).offset(1).first
end
def previous_step()
Course.find(self.course.id).course_steps.order("position DESC").where("position <= ?", self.position).limit(1).offset(1).first
end
end
How would you suggest fixing this?
What you want to do is implement your Model as a Finite State Machine and continually reload the new or edit action until the desired state is reached, then your controller can display different views depending on state to allow multiple steps to happen.
One way I have solved the problem is by adding a member action of "submit_quiz"to the course_steps controller. I am not sure if I like this, as the code looks kind of ugly. I would appreciate feedback.(Note: I Am using CanCan so #course_step is created automagically in the course_steps_controller)
The things I don't like are:
show_quiz view has a lot of code in it
submit_quiz is in the course_steps_controller
quiz_attempt model has virtual attribute of quiz_questions (for validation purposes)
show_quiz.html.erb
<%= form_for (#quiz_attempt.blank? ? QuizAttempt.new(:started => Time.now.utc, :step_quiz_id => #course_step.step.step_quiz.id) : #quiz_attempt, :url => submit_quiz_course_course_step_path(#course_step.course, #course_step)) do |f| %>
<%= render :partial => 'shared/error_messages', :object => f.object %>
<% #course_step.step.step_quiz.step_quiz_questions.each do |quiz_question| %>
<h3><%= quiz_question.value %></h3>
<% quiz_question.step_quiz_question_choices.each do |quiz_question_choice| %>
<%= radio_button_tag("quiz_attempt[quiz_questions][#{quiz_question.id}]", quiz_question_choice.value, f.object.get_quiz_question_choice(quiz_question.id) == quiz_question_choice.value)%>
<%= quiz_question_choice.value %><br />
<% end %>
<% end %>
<%= f.hidden_field(:step_quiz_id)%>
<%= f.hidden_field(:started)%>
<%= submit_tag("Submit Quiz")%>
<% end %>
course_steps_controller.rb
def show
PatientCourseStep.viewed(current_user.id, params[:course_id], #course_step.step.id )
render "show_#{#course_step.step.step_type.name.downcase}"
end
def submit_quiz
#quiz_attempt = QuizAttempt.new(params[:quiz_attempt])
if !#quiz_attempt.save()
render 'show_quiz'
end
end
quiz_attempt.rb
class QuizAttempt < ActiveRecord::Base
belongs_to :step_quiz
belongs_to :patient
attr_accessor :quiz_questions
attr_accessible :step_quiz_id, :patient_id, :started, :ended, :correct, :incorrect, :quiz_questions
validate :answered_all_questions?
def get_quiz_question_choice(quiz_question_id)
unless self.quiz_questions.blank?
quiz_questions[quiz_question_id.to_s]
end
end
private
def answered_all_questions?
#Making sure they answered all the questions
if self.quiz_questions.blank? or self.quiz_questions.try(:keys).try(:count) != self.step_quiz.step_quiz_questions.count
errors.add_to_base "Not all questions were answered"
end
end
end
def submit_quiz
#quiz_attempt = QuizAttempt.new(params[:quiz_attempt])
if !#quiz_attempt.save()
render 'show_quiz'
end
end

Resources