form_helpers Rails 3 - include objects in the loop - ruby-on-rails-3

Tour has_many :photos, Photo belongs_to :tour.
The fields for a tour are :title, :description.
The fields for a photo are :alt, :image (path), :tour_id
Tour accepts_nested_attributes_for :photos
Tour attr_accessible :photo_attributes
--
In the form for Tours, I want to return the respective Tours photos in the form once saved, so the user can see the photos they have uploaded and add their Alt Tags
This is what the form looks like, but I don't know how to bring back any saved images into the form...
= semantic_form_for ([:admin, #tour]), :html => {:multipart => true} do |f|
...
- unless #tour.new_record?
= semantic_fields_for Photo.new do |f|
= f.file_field :image, :rel => tour_photos_path(#tour)
- else
You must save the tour, to be able add photos.
= f.semantic_fields_for :photos, #tour.photos do |p|
// If there is a photo, somehow display that image in this form loop...
= image_tag ## WHAT COULD I PUT HERE? ##
= f.input :remove_image, :as => :boolean
= p.inputs
I am confused because obviously the form_helper can bring back the saved elements of the form back into the form fields.. but I don't know how I can use one of those saved elements in the image tag...

Your question is a little hard to understand, but what about something like this?
- #tour.photos.each do |photo|
= image_tag photo.path
= f.input :remove_image, :as => :boolean
# etc...

Related

Use member in rails

Hi everyone I am new with rails 3,I have a app where I want to associate a idea with a comment.
When I show an idea, in the bottom of the view I show a form to put new comment for this idea, and when a click to save a comment, I have to pass the idea_id, I create my model commment
belongs_to :user
belongs_to :idea
attr_accessible :description, :likes, :name, :user_id, :idea_id
in the view of show idea a put this
= render :partial => "comments/index", :collection => #idea.comments
= render :partial => "comments/form", :locals => {:comment=> #comment}
in the _form of the comment I include idea to obtain idea_id to save
= form_for [#idea, #comment] do |f|
and in my router I put this
resources :ideas do
member do
resources :comments
end
end
and now I obtain this error
undefined method `idea_comments_path'
any idea, anyone knows a document to explain better how to use member in rails!
You don't need member for nested resources:
resources :ideas do
resources :comments
end
http://guides.rubyonrails.org/routing.html

Rails form_for action has a corrupted locale

I have an account dashboard that lists the offices and for each office the jobs available.
Hierarchy:
Companies (1 user has 1 company, I access if from the user profile)
Offices (each company can have multiple offices)
Jobs (each office can have multiple jobs)
Models:
class Company < ActiveRecord::Base
has_many :offices, :dependent => :destroy
has_many :jobs, :through => :offices
class Office < ActiveRecord::Base
belongs_to :company
has_many :jobs, :dependent => :destroy
class Job < ActiveRecord::Base
belongs_to :office
For each job I have an edit link
E.g. for job id 10 (job is a local variable from iteration on office jobs)
= link_to edit_job_path(I18n.locale, job)
-> localhost:3000/de/jobs/10/edit
When I click on the edit link, I go to the edit page. So far so good, but the form looks like that:
<form accept-charset="UTF-8" action="/10/jobs/10" class="edit_job" enctype="multipart/form-data" id="edit_job_10" method="post">
Notice, that my locale (de in this example) disappeared and has the job id instead!
My routes.rb
scope "/:locale" do
resources :companies
resources :offices do
resources :jobs
end
resources :jobs
end
There are two jobs mentioned, I probably can do without but it's an easy way for me to either mention directly the job url to view or add office variable in the create new job link and use :office_id (in my dashboard controller: link_to new_office_job_path(I18n.locale, office) then in my form for new jobs: = f.hidden_field :office_id)
But even if I remove the resources :jobs in the :offices. The locale is still replaced by the job id in the edit form.
Note that I can edit the job properly, but because the locale is changed, the localisation text are all wrong after my redirect.
Any idea how to fix that?
------ Additional data requested -----------
= form_for(#job) do |f|
.field
= f.label :name, t(:job_title)
= f.text_field :name
.field
= f.label :url, t(:job_url)
= f.text_field :url
.field
= f.hidden_field :office_id
.field
= f.label :pdf, t(:job_upload_pdf)
= f.file_field :pdf
.field
= f.label :tag_list, t(:job_tags)
= f.text_field :tag_list
.actions
= f.submit "Submit", :class => "btn btn-primary"
------ Additional information -----------
BTW: this work around works, I get /de/jobs/10 but I'd like to understand why the locale gets corrupted if I use the default form_for.
= form_for #job, :url => job_path(I18n.locale, #job) do |f|
You can handle the locale using a Routing Filter, I've tried it in my project, you don't have to worry about locale in routes, the filter will handle it for you.
# in config/routes.rb
Rails.application.routes.draw do
filter :locale
end
I hope this will solve your problem.
The form_for line builds the path, when building the path you also need to specify the locale. To do this cleanly (without specifying the url explicitly, which is also possible), write it as follows:
= form_for [I18n.locale, #job] do |f|
and that should render the correct path.
As specified in the documentation it will use the array to build the correct path (this works for namespaced and nested routes, so I am guessing it will also work for your locale).
An alternative is to specify the path explicitly, using the :url option.
HTH.

Rails 3 polymorphic association with Carrierwave and Simple Form

I'm trying to set up a polymorphic association for photo uploads which are processed using Carrierwave. I'm using Simple Form to build my forms. I feel like the association is correct so I'm wondering if my problem is just something with the form or controller.
Here are my associations:
property.rb:
class Property < ActiveRecord::Base
attr_accessible :image
...
has_many :image, :as => :attachable
...
end
unit.rb
class Unit < ActiveRecord::Base
attr_accessible :image
...
has_many :image, :as => :attachable
end
image.rb
class Image < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
mount_uploader :image, PhotoUploader
end
properties_controller.rb:
def edit
#property = Property.find params[:id]
#property.image.build if #property.image.empty?
end
def update
#property = Property.find params[:id]
if #property.update_attributes params[:property]
redirect_to admin_properties_path, :notice => 'The property has been successfully updated.'
else
render "edit"
end
end
Snippet from properties/_form.html.erb
<%= f.input :image, :label => 'Image:', :as => :file %>
Here is the error I get when submitting with an image attached:
undefined method `each' for #<ActionDispatch::Http::UploadedFile:0x00000102291bb8>
And here are the params:
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"lvB7EMdc7juip3gBZD3XhCLyiv1Vwq/hIFdb6f1MtIA=",
"property"=>{"name"=>"Delaware Woods",
"address"=>"",
"city"=>"",
"state"=>"",
"postal_code"=>"",
"description"=>"2 bedroom with large kitchen. Garage available",
"incentives"=>"",
"active"=>"1",
"feature_ids"=>[""],
"user_ids"=>[""],
"image"=>#<ActionDispatch::Http::UploadedFile:0x00000102291bb8 #original_filename="wallpaper-4331.jpg",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"property[image]\"; filename=\"wallpaper-4331.jpg\"\r\nContent-Type: image/jpeg\r\n",
#tempfile=#<File:/tmp/RackMultipart20120608-3102-13f3pyv>>},
"commit"=>"Update Property",
"id"=>"18"}
I'm looking everywhere for help on polymorphic associations and am getting nowhere. I've seen simple examples that look pretty straight forward. One thing I've noticed is that it seems like in a lot of the examples the has_many association in my case should be images and not image. However when I do that I get an error:
Can't mass-assign protected attributes: image
I've tried updating my form to use fields_for as I've seen in other blogs like so:
<%= f.input :image, :label => "Photo", :as => :file %>
<% f.simple_fields_for :images do |images_form| %>
<%= images_form.input :id, :as => :hidden %>
<%= images_form.input :attachable_id, :as => :hidden %>
<%= images_form.input :attachable_type, :as => :hidden %>
<%= images_form.input :image, :as => :file %>
<% end %>
All I know is I'm having a heck of a time getting this to work. I'm pretty new to Rails so even debugging it is difficult. It doesn't help that the debugger doesn't really work in 3.2 :(
Since your models have_many :images (it should be :images, not :image), you'll want to use nested_forms in your views. You should set up accepts_nested_attributes_for :images on the unit and property models and change the attr_accessible from :image to :image_attributes.
Check out http://railscasts.com/episodes/196-nested-model-form-part-1 for a good guide on getting going with it.

mongoid save embedded documents

I'm trying to build up on the following tutorial from railscast:
http://railscasts.com/episodes/196-nested-model-form-part-1
I'm trying to make everything work with mongodb and mongoid.
the scenario is:
I want to creates events linked to a location. Each events (dance class) contains many lessons.
So I thought that an embedded relationship would be perfect.
Here are my models
model Lesson
class Lesson
include Mongoid::Document
include Mongoid::Slug
field :name, :type => String
embedded_in :event
slug :name
end
model Event
class Event
include Mongoid::Document
include Mongoid::Slug
include Mongoid::Timestamps
include Mongoid::MultiParameterAttributes
field :name, :type => String
field :description, :type => String
field :date, :type => DateTime
validates_presence_of :name
has_one :venue
referenced_in :venue
embeds_many :lessons
slug :name
end
model Venue
class Venue
include Mongoid::Document
include Mongoid::Slug
include Mongoid::Timestamps
include Mongoid::MultiParameterAttributes
field :name, :type => String
field :location, :type => String
validates_presence_of :name, :location
belongs_to :event
slug :name
end
event controller
def create
#event = Event.new(params[:event])
if #event.save
flash[:notice] = 'Event was successfully created.'
end
respond_with(#Event, :location => events_url)
end
def update
# #event = Event.find(params[:id])
#event = Event.find_by_slug(params[:id])
if #event.update_attributes(params[:event])
flash[:notice] = "Event was succesfully updated"
end
respond_with(#event)
end
Then I have my Event view where I can create events and link it to a Venue. But I'd like to be abe to create the lessons from the Event view/model.
so I used the fields_for to generate a field linked to the Lessons model.
= form_for #event do |f|
.field
= f.label :name
%br/
= f.text_field :name
.field
= f.label :description
%br/
= f.text_area :description
.field
= f.label :venue_id
%br/
= f.collection_select :venue_id, Venue.all, :id, :name
.field
= f.label :date
%br/
= f.datetime_select :date
%h3 Add a Class
= f.fields_for :lessons do |builder|
= render "lesson_fields", :f => builder
.actions
= f.submit 'Save'
When I create or edit a new event I get an error message:
undefined method `extract_id' for "test":String
But the request parameter message on the error page shows my lessons value in the Event document.
"lessons"=>{"name"=>"test name lesson"}
When I remove the fields_for line, everything works fine. But then i don't know how to save the value for the nested documents.
I have same problem with embeds_many, but when i try change to has_many. It works!. Maybe you can try too.
can you post the exact code you use to create the Event, including parameters?
which version of Mongoid and Rails are you using?
First thing I noticed is that the following parameter hash does not match your Lessons model:
"lessons"=>{"content"=>"test name lesson"} # this looks wrong
this should be:
"lessons"=>{"name" => "test name lesson"}
Looks like your lessons form has the wrong label for the text input field .. it should be :name , not :content
To dry things up, you might want to try if the 'nested_form' gem works for you:
after installing the gem, use the nested_form_for instead of form_for in your view.
Check here for a more detailed description:
How can I handle this type of multi level forms in rails
See:
https://github.com/ryanb/nested_form (it's also referenced in the RailsCast you mentioned)
You also might want to check this:
field_for and nested form with mongoid
The conclusion of this story is...
I removed everything related to mongoid_slug and it started to work.
I then put everything back as it was to try to find out how to make it work with mongoid_slug and it just worked, like out of the box.
:(
Please include the following code in model event.rb
**accepts_nested_attributes_for :lessons**
This will fix your problem

Rails 3 & paperclip - not rendering images

I've just started using Paperclip today and am having issues getting images to render. After some wrangling the photos are saving in the correct directory but there is a routing/rendering error:
ActionController::RoutingError (No route matches "/public/system/products/19/original/puppies-3.jpg")
However, the images are definitely saving in the correct directory. This is what's in my product model:
class Product < ActiveRecord::Base
validates :title, :presence => true
validates :description, :presence => true
validates :category, :presence => true
validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 5.megabytes
attr_accessible :photo, :photo_file_name, :photo_content_type, :photo_file_size, :photo_updated_at
attr_accessible :title, :description, :category, :price
has_attached_file :photo, :styles => { :small => "150x150>", :large => "400x400>" },
:path => ":rails_root/public/system/products/:id/:style/:basename.:extension",
:url => "/system/products/:id/:style/:basename.:extension"
end
This is in my view:
<%= image_tag #product.photo.url %>
At the moment it's simply returning the image basename instead of the image itself, any thoughts? Products is available as a resource in routes.rb, but do I need to explicitly make photos available also somehow? I'm also fairly new to Rails so struggling a little bit...
Are you sure that product with that id has a image attached? I think some of your products dont have images attached but u still looking for them. Maybe try to set a default_url. Something like this:
has_attached_file :photo, :default_url => "/images/missing.png"
This will show that image set in default_url for the products what dont have images attached.
It's ok, I've fixed it. I had left a field in my form which was naming the photo_file_name from when I couldn't get the files to save and was trying to manually override it to get it to work (face-palm). It's amazing how much clarity comes from a few hours sleep.