undefined method `has_many' for Formtastic - ruby-on-rails-3

I'm getting this error :
undefined method `has_many' for #<Formtastic::SemanticFormBuilder:0xb410d4c>
It work when I use it like this :
ActiveAdmin.register Ressource do
form do |f|
f.inputs do
f.input :offer_id, :as => :hidden
f.input :name
f.input :category, :include_blank => false, :collection => Category.order('place ASC').all, :member_label => :to_label
f.input :description, :input_html => {:class => 'editor'}
f.input :price
end
f.has_many :roles do |app_f|
app_f.inputs do
if not app_f.object.id.nil?
app_f.input :_destroy, :as => :boolean, :label => "Supprimer l'utilisateur du lot"
end
app_f.input :user, :member_label => :to_label, :label => 'Assigné le lot'
app_f.input :name, :include_blank => false
end
end
f.buttons
end
end
But it doesn't work in a partial, i need to call the has_many method by a different way or something else ?

ActiveAdmin extends formtastic with some useful helpers such as has_many (lib/active_admin/form_builder.rb in the activeadmin gem).
Unfortunately, these helpers are not available by default in your templates.
Here are two options:
If you don't need the extra has_many functionality (it looks like active_admin adds some javascript to make it easy to add a new record to the collection), then you can use stock formtastic. This example should work fine in the activeadmin file as well as in a partial:
ActiveAdmin.register Ressource do
form do |f|
# ...
f.inputs :for => :roles do |app_f|
# ...
app_f.input :name, :include_blank => false
end
f.buttons
end
end
Use the ActiveAdmin form builder explicitly:
<%= semantic_form_for [:admin, #resource], builder: ActiveAdmin::FormBuilder do |f| %>
<!-- ... -->
<%= f.has_many :teachers do |app_f| %>
<%= app_f.inputs do %>
<!-- ... -->
<% end %>
<% end %>
<%= f.buttons %>
<% end %>
I hope this helps.

There is a solution
form :html => {:multipart => true} do |f|
end
Or, if you want to use partial:
<%= active_admin_form_for [:admin, #resource] ,:html => {:multipart => true} do |f|%>
<% end %>

Related

when using semantic_form_for accurs "ActionView::Template::Error (undefined method `my_leaders_path' for #<#<Class...)"

model:
class MyLeader < ActiveRecord::Base
extend Enumerize
belongs_to :interviewer
attr_accessible :interviewer_id, :is_leader, :content
enumerize :is_leader, :in => %w[yes no]
end
controller:
ActiveAdmin.register MyLeader, :namespace => :fieldwork do
form do |f|
render :partial => 'content'
end
end
rake routes:
batch_action_fieldwork_my_leaders POST /fieldwork/my_leaders/batch_action(.:format) fieldwork/my_leaders#batch_action
fieldwork_my_leaders POST /fieldwork/my_leaders(.:format) fieldwork/my_leaders#create
new_fieldwork_my_leader GET /fieldwork/my_leaders/new(.:format) fieldwork/my_leaders#new
edit_fieldwork_my_leader GET /fieldwork/my_leaders/:id/edit(.:format) fieldwork/my_leaders#edit
fieldwork_my_leader GET /fieldwork/my_leaders/:id(.:format) fieldwork/my_leaders#show
PUT /fieldwork/my_leaders/:id(.:format) fieldwork/my_leaders#update
DELETE /fieldwork/my_leaders/:id(.:format) fieldwork/my_leaders#destroy
_content.html.erb:
<div style="width:80%;margin-left:400px">
<%= semantic_form_for MyLeader.new do |f| %>
<%= f.input :interviewer_id, :as => :hidden%>
<%= f.input :is_leader%>
<%= f.actions do %>
<%= f.action :reset, :as => :button %>
<%= f.action :submit, :as => :button %>
<% end %>
<% end %>
The ERROR is:
ActionView::Template::Error (undefined method `my_leaders_path' for #<#<Class:0x007fadc5f8cdf0>:0x007fadc3d929e8>):
Why this happened: undefined method `my_leaders_path'?
should that be fieldwork_my_leaders_path?
Seems like your form cost you an issue.
Here is example from documentation.
Partials
If you want to split a custom form into a separate partial use:
ActiveAdmin.register Post do
form partial: 'form'
end
Which looks for something like this:
app/views/admin/posts/_form.html.arb
active_admin_form_for resource do |f|
inputs :title, :body
actions
end
This is a regular Rails partial so any template engine may be used.
Make sure that you put _content.html.erb in right folder.

How to write routes with model inherit

I have a model in app/models/post.rb
class Post < ActiveRecord::Base
end
And I have another model in app/models/post/note.rb
class Post::Note < Post
mount_uploader :file, FileUploader
end
In my controller :
def new
#note = Post::Note.new
end
My view form is :
<%= simple_form_for #post, :validate => true, :html => {:class => 'form-horizontal'} do |form| %>
<%= form.input :title, :validate => {:presence => true} %>
<%= form.button :submit %>
<% end %>
The error is undefined methodpost_notes_path' for #<#:0x007fe3d3fe2b08>`
I want to know how to write the correct route config ?
You can specify the url as an option to simple_form, to override the default path it uses. So if your Post::Note model has a path helper note_path, then this should work:
<%= simple_form_for #post, :url => note_path, :validate => true, :html => {:class => 'form-horizontal'} do |form| %>
<%= form.input :title, :validate => {:presence => true} %>
<%= form.button :submit %>
<% end %>
Ref: How do you handle single table inheritance in SimpleForm so a single helper handles all models?

Can't mass-assign protected attributes: asset

I followed the tutorial screencast over here: http://www.emersonlackey.com/article/rails-paperclip-multiple-file-uploads. I want my model have multiple pictures upload show up.
I have examined carefully every steps, the most common issue is forget to add assets_attributes to attr_accessible, I have done that. Another issues might bbe forgot to add ID to asset model, i done that too. However, I still have trouble understanding why it happen.
Can't mass-assign protected attributes: asset in app/controllers/posts_controller.rb:24:in `update'
I have already add list of all attributes for a Post to post model. Like:
class Post < ActiveRecord::Base
attr_accessible :name, :content, :assets_attributes
validates :user_id, presence: true
belongs_to :user
has_many :assets
accepts_nested_attributes_for :assets, :allow_destroy => true
default_scope order: 'posts.created_at DESC'
end
Here is the post_controller.rb file:
def edit
#post = Post.find(params[:id])
5.times { #post.assets.build }
end
def update
#post = Post.find(params[:id])
if #post.update_attributes(params[:post])
redirect_to #post, :notice => "Post has been updated."
end
def create
post = current_user.posts.build(params[:post])
if post.save
flash[:success] = "post created success!"
redirect_to #post
else
#feed_items = []
flash[:failure] = "post created fail!"
redirect_to root_path
end
end
def new
#post = current_user.posts.new #if signed_in?
5.times { #post.assets.build }
end
Here is the template file:
<%= simple_form_for(#post, :html => {:multipart => true}) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :content %>
<%= f.text_field :content %>
<%= f.simple_fields_for :assets, :html => { :multipart => true } do |asset_fields| %>
<% if asset_fields.object.new_record? %>
<P><%= asset_fields.file_field :asset %> </P>
<% end %>
<% end %>
<%= f.simple_fields_for :assets, :html => { :multipart => true } do |asset_fields| %>
<% unless asset_fields.object.new_record? %>
<P><%= link_to image_tag(asset_fields.object.asset.url(:thumb)), asset_fields.objects.asset.url(:original) %>
<%= asset_fields.check_box :_destroy %></P>
<% end %>
<% end %>
Below is asset.rb:
class Asset < ActiveRecord::Base
belongs_to :post
has_attached_file :asset,
:style => { :large => "640x480", :medium => "300x300", :thumb => "100x100"} ,
:path => ":rails_root/public/system/posts/images/:id/:style/:filename",
:url => "/system/posts/images/:id/:style/:filename"
end
Can someone give me some hint ? Thanks a lot!
Your Asset model needs to have attr_accessible on it too - specifically for the asset field.

Default value on select field in formtastic form with no model

I have a formtastic form to gather parameters for report generation. I know formtastic is designed to be used with models but I need to use it here as the form is in an activeadmin page.
It's all working well but I can't set a default value for the selects. I'm willing to implement a "despicable hack" to get this working. I'd prefer not to implement a fake model
just to set default values on a form.
The form code looks like this
<%= semantic_form_for "report", :url => report_admin_payments_path do |f| %>
<%= f.inputs do %>
<%= f.input :report_type, :as => :select, :collection => report_types, :input_html => {:style => "width:180px"} %>
<%= f.input :start_date, :as => :string, :input_html => {:class => 'datepicker', :style => "width:60px", :value => 1.month.ago.strftime("%Y-%m-%d")} %>
<%= f.input :end_date, :as => :string, :input_html => {:class => 'datepicker', :style => "width:60px", :value => Time.zone.now.strftime("%Y-%m-%d")} %>
<%= f.input :country, :as => :select, :collection => locales, :input_html => {:style => "width:180px"}%>
<% end %>
<%= f.actions :submit %>
<% end %>
Thanks in advance,
Matt
This or something similar should meet your needs.
class LightModel
# Subclass this for a model that looks like an ar model but has no persistence
# good for formtastic forms
include ActiveModel::Naming
include ActiveModel::Validations
def initialize(attributes = {})
#attributes = attributes
end
# read only atm
def method_missing(m, *args, &block)
#attributes[m]
end
end
Thanks,
Matt

Rails: Validation for a simple_form using has_many relationship (e.g. Person, Phone)

I'm struggling getting the desired validation with nested models within a simple_form. You'll be able to see from the models below a Person can have many Phone's, the desired behaviour is to present edit fields for any existing numbers plus an additional one should for a new number, if this new number isn't filled in by the user then it's just ignore and not saved in the database. I also want to achieve similar with Email.
When landing on the /people/:id/edit page this blank field is being prematurely validated and producing visible errors on the form before submitting. It doesn't do this when visiting /people/:id/new page; I'm assuming that this is because new_record? returns true for the user model on the new page? In reading a similar post I added on: :save as a parameter to validates on the Phone model although this just allowed blank records into the database, perhaps because this isn't relevant when the user model is saving the record?
class Person < ActiveRecord::Base
belongs_to :company
has_many :phones, :as => :phoneable
has_many :emails, :as => :emailable
has_many :addresses, :as => :addressable
attr_accessible :first_name, :job_title, :last_name, :prefix, :phones_attributes, :emails_attributes, :addresses_attributes, :company_id
accepts_nested_attributes_for :phones, allow_destroy: true, reject_if: proc { |attributes| attributes['number'].blank? }
accepts_nested_attributes_for :emails, allow_destroy: true, reject_if: proc { |attributes| attributes['email'].blank? }
accepts_nested_attributes_for :addresses, allow_destroy: true, reject_if: :all_blank
validates :first_name, :last_name, presence: true
def to_s
"#{first_name} #{last_name}"
end
end
class Phone < ActiveRecord::Base
belongs_to :phoneable, polymorphic: true
attr_accessible :number, :phone_type
validates :number, :phone_type, presence: true, on: :save # as suggested in a similar post, just allows blank records into database.
def to_s
"#{phone_type}: #{number}"
end
end
With both the new and edit controller I'm creating a new instance of each of these models so that they show up on the form. #person is loaded in the controller using load_and_authorize_resource as part of cancan.
def new
#person.phones << Phone.new
#person.emails << Email.new
end
Here is the partial view for the form:
<%= simple_form_for #person, :html => { :class => 'form-horizontal' } do |f| %>
<fieldset id="<%= controller.action_name.capitalize %>_person">
<legend><%= controller.action_name.capitalize %> Person</legend>
<%= f.input :prefix %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :job_title %>
<%= f.association :company, :prompt => "Select associated company..." %>
<%= f.simple_fields_for :phones do |phone| %>
<%= phone.input :phone_type, :collection => %w(Work Home Mobile Fax Other), :default => "Work" %>
<%= phone.input :number %>
<% end %>
<%= f.simple_fields_for :emails do |email| %>
<%= email.input :email_type, :collection => %w(Work Home Other), :default => "Work" %>
<%= email.input :email %>
<% end %>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
people_path, :class => 'btn' %>
</div>
</fieldset>
<% end %>
Many thanks for any help in advance :-)