How to write routes with model inherit - ruby-on-rails-3

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?

Related

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.

Rails 3 + Simple Form: Specifiy label class when using f.association

How can I specify the label class when using f.association instead of f.input in simple_form?
For example, this works:
f.input :name, :label_html => { :class => 'some-class' }
But this doesn't
f.association :periods, :as => :check_boxes, :label_html => { :class => 'some-class' }
Meaning that the label related to :name will have some-class as part of its class, but the label related to :periods won't. Any way to do this without changing f.association to f.input? Thank!
I think you can't add custom class to each label but you can do it for each item wrapper, e.g:
<%= simple_form_for(#user) do |f| %>
<%= f.association :group, as: :check_boxes, item_wrapper_class: 'custom-class' %>
<%= f.button :submit %>
<% end %>

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

Submitting AJAX form for a nested child with another nested child (AssociationTypeMismatch)

My models
I'm trying to create a form for an Annotation. This annotation belongs to a Map, and each annotation should have one Boundary. A map can have many annotations.
I first created the association by letting both Annotation and Map has_one Boundary, but later I switched to using a polymorphic boundary_object. The error was the same regardless.
has_one :boundary, :as => :boundary_object # <= Map
has_one :boundary, :as => :boundary_object # <= Annotation
belongs_to :boundary_object, :polymorphic => true # <= Boundary
Views and Controller
Here's the thing: First I used Boundary.new to create a new boundary object here, since I didn't have a pre-set annotation object, since the form can be submitted multiple times.
maps/show.html.erb
<%= form_for([#map, Annotation.new], :remote => true ) do |f| %>
<%= f.text_area :body, :cols => 80, :rows => 10, :style => "width: 500px" %>
<%= f.fields_for Boundary.new do |b| %>
<%= b.text_field :ne_x, :style => "display:none" %>
<%= b.text_field :ne_y, :style => "display:none" %>
<%= b.text_field :sw_x, :style => "display:none" %>
<%= b.text_field :sw_y, :style => "display:none" %>
<% end %>
<% end %>
I could use f.fields_for :boundary too, if I have this in the maps_controller.rb:
#annotation = #map.annotations.build
#annotation.boundary = Boundary.new
But the result is still the same.
annotations_controller.rb
def create
#annotation = Annotation.new(params[:annotation])
respond_to do |format|
if #annotation.save
format.js { }
end
end
The Error
When submitting that form, this results in the following error at the first line in the create method.
ActiveRecord::AssociationTypeMismatch (Boundary(#2158793660) expected, got ActiveSupport::HashWithIndifferentAccess(#2165684420))
Obviously, the form works without the whole boundary thing. These are the parameters submitted:
{
"utf8"=>"✓",
"authenticity_token"=>"6GDF6aDc6GMR3CMP+QzWKZW9IV9gSxfdkxipfg39q7U=",
"annotation"=>
{
"body"=>"foo bar",
"boundary"=>
{
"ne_x"=>"11312",
"ne_y"=>"5919",
"sw_x"=>"6176",
"sw_y"=>"1871"
}
},
"map_id"=>"1"
}
What do I have to do to be able to create the Boundary object for this annotation right away?
According to your associations:
First, you need to build a new boundary object (see here for more info):
def show
#map = ...
#annotation = #map.annotations.build
#boundary = #annotation.build_boundary # build new boundary
end
Second, you need to edit your view:
<%= form_for([#map, #annotation], :remote => true ) do |f| %>
<%= f.text_area :body, :cols => 80, :rows => 10, :style => "width: 500px" %>
<%= f.fields_for :boundary do |b| %>
...
<% end %>
<% end %>
Third, check that you have accepts_nested_attributes_for for your Boundary in the Annotation model.
accepts_nested_attributes_for :boundary
The form will then look like this – note that the name of the association needs _attributes:
<input … name="annotation[boundary_attributes][ne_x]" … />

undefined method `has_many' for Formtastic

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 %>