I have this structure models
class Tournament < ActiveRecord::Base
AGES = ["5u", "6u", "7u", "8u"]
has_many :courts, :dependent => :destroy
accepts_nested_attributes_for :courts, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
class Court < ActiveRecord::Base
belongs_to :tournament, :autosave => true
has_many :ages, :dependent => :destroy
accepts_nested_attributes_for :ages, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
class Age < ActiveRecord::Base
belongs_to :court
Now my forms look like this
_form.html.erb
<%= semantic_form_for #tournament do |f| %>
<%= f.inputs do %>
<%= f.input :name, :hint => "What is the name of the Tournament?" %>
<%= f.semantic_fields_for :courts do |builder| %>
<%= render :partial => "court_fields", :locals => { :f => builder } %>
<% end %>
_court_fields.html.erb
<div class="nested_fields">
<%= f.input :name, :input_html => {:class => "name"} %>
<%= f.semantic_fields_for :ages do |builder| %>
<%= render :partial => "age_fields", :locals => { :f => builder } %>
<% end %>
_age_fields.html.erb
Testing ...am I getting in here
<%= f.input :name, :as => :check_boxes, :collection => Tournament::AGES, :input_html => {:class => "age_limits"} %>
everything seems to work well except nothing shows up in the ages_fields partial...not the checkboxes and not even the dummy text Testing ...am I getting in here is not displaying....any ideas what could be causing the issue
The obvious reason I can think of: are you sure your Court has ages ?
[EDIT] That the Court has the relation was indeed clear to me.
But your code will only show an age for a court if it already exists.
From your output in the comments: the court has no actual ages so no ages are shown.
If you do this in your controller:
def new
#tournament = Tournament.new
#tournament.courts.build
#tournament.courts[0].ages.build
end
This will make sure that you have at least one (empty) court and one (empty) age.
Otherwise you could also consider using a gem like cocoon to dynamically add new elements if needed.
Hope this helps.
Related
class Resume < ActiveRecord::Base
has_many :user_skills, :dependent => :destroy
accepts_nested_attributes_for :user_skills, :allow_destroy => true, :reject_if => :all_blank
end
class UserSkill < ActiveRecord::Base
belongs_to :resume
has_and_belongs_to_many :technologies
end
class Technology < ActiveRecord::Base
has_and_belongs_to_many :user_skills
end
<%= nested_form_for([:student, #resume], validate: true, :html => { :multipart => true, class: "full-width" }) do |f| %>
------------------------------
Resume fields
------------------------------
<h5>User Skills</h5>
<%= f.fields_for :user_skills do |us| %>
<%= us.label :academic_years, "Academic Years" %>
<%= us.text_field :academic_years %>
<%= us.label :professional_years, "Professional Years" %>
<%= us.text_field :professional_years %>
<%= us.fields_for :technologies do |tech| %>
<%= tech.collection_select :name, Technology.all, :id, :name, { prompt: "Select Technology"}, { :multiple => true, :size => 10} %>
<% end %>
<%= us.link_to_remove "Remove", class: "btn btn-small red right" %>
Now I don't know how I manage this record in controller for create and update, And also I don't know how will I show this records.... If you understand my problem then pleasr provide me controller code for update and create of resume controller and also help me to show the resume data.
I think you use old nested_form gem by Ryan Bates. You should use newest for example simple_form or others from ruby-toolbox.com
I have two models, Developers and Tasks,
class Developer < ActiveRecord::Base
attr_accessible :address, :comment, :email, :name, :nit, :phone, :web
has_many :assignments
has_many :tasks, :through => :assignments
end
class Task < ActiveRecord::Base
attr_accessible :description, :name, :sprint_id, :developer_ids
has_many :assignments
has_many :developers, :through => :assignments
end
class Assignment < ActiveRecord::Base
attr_accessible :accomplished_time, :developer_id, :estimated_time, :status, :task_id
belongs_to :task
belongs_to :developer
end
im taking care of the relation by adding an Assignment table, so i can add many developers to one task in particular, now i would also like to be able to manipulate the other fields i added to the joining table like the 'estimated_time', 'accomplished_time'... etc... what i got on my Simple_form is
`
<%= simple_form_for [#sprint,#task], :html => { :class => 'form-horizontal' } do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.association :developers, :as => :check_boxes %>
<div class="form-actions">
<%= f.button :submit, :class => 'btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
project_sprint_path(#sprint.project_id,#sprint), :class => 'btn' %>
</div>
<% end %>`
This only allows me to select the developers, i want to be able to modify the estimated_time field right there.
Any Suggestions?
I love how simple-form has the association helpers, making it really easy in some cases. Unfortunately, what you want you cannot solve with just simple-form.
You will have to create assignments for this to work.
There are two possible approaches.
For both you will have to add the following to your model:
class Task
accepts_nested_attributes_for :assignments
end
Note that if you are using attr_accesible, you should also add assignments_attributes to it.
The easy approach
Suppose you know how many assignments, maximally, a task would have. Suppose 1 for simplicity.
In your controller, write
def new
#task = Task.build
#task.assignments.build
end
This will make sure there is one new assignment.
In your view write:
= simple_form_for [#sprint,#task], :html => { :class => 'form-horizontal' } do |f|
= f.input :name
= f.input :description
= f.simple_fields_for :assignments do |assignment|
= assignment.association :developer, :as => :select
= assignment.estimated_time
.form-actions
= f.button :submit, :class => 'btn-primary'
= link_to t('.cancel', :default => t("helpers.links.cancel")),
project_sprint_path(#sprint.project_id,#sprint), :class => 'btn'
The problem with this approach: what if you want more than 1, 2 or 3?
Use cocoon
Cocoon is a gem that allows you to create dynamic nested forms.
Your view would become:
= simple_form_for [#sprint,#task], :html => { :class => 'form-horizontal' } do |f|
= f.input :name
= f.input :description
= f.simple_fields_for :assignments do |assignment|
= render `assignment_fields`, :f => assignment
.links
= link_to_add_association 'add assignment', f, :assignments
.form-actions
= f.button :submit, :class => 'btn-primary'
= link_to t('.cancel', :default => t("helpers.links.cancel")),
project_sprint_path(#sprint.project_id,#sprint), :class => 'btn'
And define a partial _assignment_fields.html.haml :
.nested_fields
= f.association :developer, :as => :select
= f.estimated_time
= link_to_remove_association 'remove assignment', f
Hope this helps.
The thing is that by using this:
<%= f.association :developers, :as => :check_boxes %>
You're actually only setting the developer_ids attribute, which will automatically build the assignments for you as it's a has many :through. For this I believe you should probably be using nested attributes, for each of the assignments, and each record would have a select box or similar to choose the related developer for that particular assignment in this task. It's quite similar to what Cojones has answered, but you should not be using check boxes for this association, since you're going to be dealing with a single assignment which contains a single developer. And with nested attributes, you should be able to create as many assignments you want.
That I believe is the easiest way to start with.
I think it should look somehow like this:
= f.simple_fields_for :assignments do |fa|
= fa.association :developer, as: :check_boxes
= fa.input :estimated_time
...
I have been developing a rails app that uploads and processes images. Images, along with other string information is submitted via a form_for. I've been researching this topic for about 16 hours now and no solution has worked. Honestly it's like rails isn't even reading my code.
One Processmodel has many Assets, where an Asset is just a model to hold one image file. When creating processmodels, I can never access the asset, always recieving the cannot mass-assign attirbutes: assets_attributes
Completed 500 Internal Server Error in 13ms
ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: asset):
app/controllers/process_controller.rb:20:in `new'
app/controllers/process_controller.rb:20:in `create'
-
This form is used in new.html.erb
<%= semantic_form_for #processmodel, :url => { :action => 'create' }, :html => { :multipart => true } do |f| %>
<%= f.input :batch, :as => :string, :name => "Batch" %>
<%= f.input :batchset, :as => :string, :name => "Batchset" %>
<%= f.input :numSlots, :as => :number, :name => "Number of slots" %>
<%= f.input :key, :as => :file, :name => "Key" %>
<%= f.semantic_fields_for :asset do |asset| %>
<%= asset.input :asset, :as => :file, :label => "Image" %>
<% end %><br />
<%= f.submit %>
<% end %>
-
class Processmodel < ActiveRecord::Base
attr_accessible :user_id, :batch,
:batchset, :numSlots,
:key,:assets_attributes
attr_accessor :key_file_name
has_many :assets, :dependent => :destroy
belongs_to :user
has_attached_file :key
# :url => Rails.root.join('/assets/readimages/:basename.:extension'),
# :path => Rails.root.join('/assets/readimages/:basename.:extension'),
accepts_nested_attributes_for :assets, :allow_destroy => true
.
.
.
end
-
require 'RMagick'
class Asset < ActiveRecord::Base
attr_accessible :results_string,
:name,
:ambiguous_results,
:image
belongs_to :batch_element
belongs_to :processmodel
has_attached_file :image
validates_attachment_presence :image
end
-
class ProcessController < ApplicationController
def create
#Processmodel = Processmodel.new(params[:processmodel])
#Processmodel.save
all_img = Array.new(#processmodel.assets.all)
respond_to do |format|
if #processmodel.beginRead(...)
redirect_to :action => 'results_main', :controller => 'results'
else
format.html { render action: "new" }
end
end
end
-
def new
#processmodel = Processmodel.new
#5.times{#processmodel.assets.build}
respond_to do |format|
format.html #new.html.erb
end
end
Am requesting an ideas on how to fix this and get my app working.
You need to update your database migration. Run:
rails g migration AddIdToAsset processmodel_id:integer
rake db::migrate
You've called your attached file :image here:
has_attached_file :image
But you call it :asset in your view:
<%= asset.input :asset, :as => :file, :label => "Image" %>
To fix, just change this line to
<%= asset.input :image, :as => :file, :label => "Image" %>
Here's the structure of my code. I have a video attached with each cresponse and as far as I can tell I have been successful in uploading it. The problem comes when I need to convert it after the structure is saved. I wish to access the newly updated nested attribute (see lesson_controller) but am not sure how to go about doing so.
Many thanks!
Pier.
lesson.rb
class Lesson < ActiveRecord::Base
has_one :user
has_many :comments, :dependent => :destroy
has_many :cresponses, :dependent => :destroy
acts_as_commentable
accepts_nested_attributes_for :comments, :reject_if => lambda { |a| a[:body].blank? }, :allow_destroy => true
accepts_nested_attributes_for :cresponses
and here's cresponse.rb
class Cresponse < ActiveRecord::Base
belongs_to :lesson
attr_accessible :media, :accepted, :description, :user_id
# NOTE: Comments belong to a user
belongs_to :user, :polymorphic => true
# Paperclip
require 'paperclip'
has_attached_file :media,
:url => "/system/:lesson_id/:class/:basename.:extension",
:path => ":rails_root/public/system/:lesson_id/:class/:basename.:extension"
Here's my HTML view
<% #cresponse = #lesson.cresponses.build %>
<%= form_for #lesson, :html => { :multipart => true } do |f| %>
<td class="list_discussion" colspan="2">
<div class="field">
<%= f.fields_for :cresponses, #cresponse, :url => #cresponse, :html => { :multipart => true } do |builder| %>
Upload : <%= builder.file_field :media %><br />
Description : <%= builder.text_field :description %>
<%= builder.hidden_field :user_id , :value => current_user.id %>
<% end %>
</div>
</td>
and here's lesson_controller.rb - update
def update
#lesson = Lesson.find(params[:id])
respond_to do |format|
if #lesson.update_attributes(params[:lesson])
**if #lesson.cresponses.** <-- not sure how to find the cresponse that I need to convert
puts("Gotta convert this")
end
Think I should answer my own question ..
Basically for lesson_controller.rb
params[:lesson][:cresponses_attributes].values.each do |cr|
#cresponse_user_id = cr[:user_id]
#cresponse_description = cr[:description]
if cr[:media]
.... and so on
I'm trying to get it to work but it dosen't!
I have
class User < ActiveRecord::Base
has_many :events, :through => :event_users
has_many :event_users
accepts_nested_attributes_for :event_users
end
class Event < ActiveRecord::Base
has_many :event_users
has_many :users, :through => :event_users
accepts_nested_attributes_for :users
end
class EventUser < ActiveRecord::Base
set_table_name :events_users
belongs_to :event
belongs_to :user
accepts_nested_attributes_for :events
accepts_nested_attributes_for :users
end
And also the table-layout
event_users
user_id
event_id
user_type
events
id
name
users
id
name
And this is my form
<%= semantic_form_for #event do |f| %>
<%= f.semantic_fields_for :users, f.object.users do |f1| %>
<%= f1.text_field :name, "Name" %>
<%= f1.semantic_fields_for :event_users do |f2| %>
<%= f2.hidden_field :user_type, :value => 'participating' %>
<% end %>
<% end %>
<%= link_to_add_association 'add task', f, :users %>
<% end %>
The problem is that if I create a new user this way, it doesn't set the value of user_type (but it creates a user and a event_users with user_id and event_id). If I go back to the edit-form after the creation of a user and submit, then the value of user_type is set in events_users. (I have also tried without formtastic)
Any suggestions? Thanks!
----edit----
I have also tried to have the event_users before users
<%= semantic_form_for #event do |f| %>
<%= f.semantic_fields_for :event_users do |f1| %>
<%= f1.hidden_field :user_type, :value => 'participating' %>
<%= f1.semantic_fields_for :users do |f2| %>
<%= f2.text_field :name, "Name" %>
<% end %>
<% end %>
<%= link_to_add_association 'add task', f, :event_users %>
<% end %>
but then it only throws me an error:
User(#2366531740) expected, got
ActiveSupport::HashWithIndifferentAccess(#2164210940)
--edit--
the link_to_association is a formtastic-cocoon method (https://github.com/nathanvda/formtastic-cocoon) but I have tried to do other approaches but with the same result
---edit----
def create
#event = Event.new(params[:event])
respond_to do |format|
if #event.save
format.html { redirect_to(#event, :notice => 'Event was successfully created.') }
format.xml { render :xml => #event, :status => :created, :location => #event }
else
format.html { render :action => "new" }
format.xml { render :xml => #event.errors, :status => :unprocessable_entity }
end
end
end
To be honest, i have never tried to edit or create a has_many :through in that way.
It took a little while, and had to fix the js inside formtastic_cocoon to get it working, so here is a working solution.
You need to specift the EventUser model, and then fill the User model (the other way round will never work).
So inside the models you write:
class Event < ActiveRecord::Base
has_many :event_users
has_many :users, :through => :event_users
accepts_nested_attributes_for :users, :reject_if => proc {|attributes| attributes[:name].blank? }, :allow_destroy => true
accepts_nested_attributes_for :event_users, :reject_if => proc {|attributes| attributes[:user_attributes][:name].blank? }, :allow_destroy => true
end
class EventUser < ActiveRecord::Base
belongs_to :user
belongs_to :event
accepts_nested_attributes_for :user
end
class User < ActiveRecord::Base
has_many :events, :through => :event_users
has_many :event_users
end
Then the views. Start with the events/_form.html.haml
= semantic_form_for #event do |f|
- f.inputs do
= f.input :name
%h3 Users (with user-type)
#users_with_usertype
= f.semantic_fields_for :event_users do |event_user|
= render 'event_user_fields', :f => event_user
.links
= link_to_add_association 'add user with usertype', f, :event_users
.actions
= f.submit 'Save'
(i ignore errors for now)
Then, you will need to specify the partial _event_user_fields.html.haml partial (here comes a little bit of magic) :
.nested-fields
= f.inputs do
= f.input :user_type, :as => :hidden, :value => 'participating'
- if f.object.new_record?
- f.object.build_user
= f.fields_for(:user, f.object.user, :child_index => "new_user") do |builder|
= render("user_fields", :f => builder, :dynamic => true)
and to end the _user_fields partial (which does not really have to be a partial)
.nested-fields
= f.inputs do
= f.input :name
This should work.
Do note that i had to update the formtastic_cocoon gem, so you will need to update to version 0.0.2.
Now it would be easily possible to select the user_type from a simple dropdown, instead of a hidden field, e.g. use
= f.input :user_type, :as => :select, :collection => ["Participator", "Organizer", "Sponsor"]
Some thoughts (now i proved it works):
this will always create new users on the fly, actually eliminating the need for the EventUser. Will you allow selecting existing users from a dropdown too?
personally i would turn it around: let users assign themselves to an event!
Does the events_users model not have an ID column? Since there's an additional field (user_type) then EventUser is a model and should probably have an ID. Maybe that's why user_type isn't being set in your first case.