Im creating a website where a User can post an ad of a Property , which can have many Photos .
I have been on this problem for 2 days now , none of the answers I've found have worked for this problem.
Heres the main program from where the issue is I believe . I have tested many different versions from this code and none have been successful .
The params hash in the console returns correct values , its just the manipulation of it causes the problems .
{"utf8"=>"✓", "authenticity_token"=>"3OWguFpgwOYaLmQ4szRmPK/i13kLRr4XT1hcU6YEVlgml1iK1OzAg5c9UyETK1MiqdpoHYLcDGgx4aGd/FaZJg==",
"property"=>{ "title"=>"asda", "price"=>"3", "numberOfBeds"=>"4", "toilets"=>"34", "description"=>"salads", "photo"=>{"property_pic"=>#, @original_filename="ASC_0321.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"property[photo][property_pic]\"; filename=\"ASC_0321.jpg\"\r\nContent-Type: image/jpeg\r\n">}}, "commit"=>"Create Ad"}
property.rb
class Property < ActiveRecord::Base
belongs_to :user
has_many :photos , dependent: :destroy
accepts_nested_attributes_for :photos , reject_if: lambda {|t| t['photo'].nil?
}
end
properties_controller.rb
def new
@property = Property.new
@photo = @property.photos.new
end
def create
@property = current_user.properties.new(params[:property])
@property.photos.new(params[[:photo][:property_pic]])
if @property.save
redirect_to property_path @property
else
render :edit
end
end
def property_params
params.require(:property).permit(:title,:price,:numberOfBeds,:toilets,:description , photo:[:property_pic])
end
properties/new.html.erb
<div class="wrapper_skinny">
<%= form_for @property do |p| %>
<%= p.label :title %>
<%= p.text_field :title %> <br><br>
<%= p.label :price %>
<%= p.number_field :price %> <br><br>
<%= p.label :numberOfBeds %>
<%= p.number_field :numberOfBeds %> <br><br>
<%= p.label :toilets %>
<%= p.number_field :toilets %> <br><br>
<%= p.label :description %>
<%= p.text_area :description %> <br><br>
<%= p.fields_for :photo do |builder| %>
<%= builder.label :property_pic %>
<%= builder.file_field :property_pic %>
<% end %> <br><br>
<%= p.submit "Create Ad" , class:"button button-chosen"%>
<% end %>
</div>
Thanks!
photo:
in yourproperty_params
method tophotos_attributes:
? That could be the cause of some issues. - Zoran<%= p.fields_for :photos %>
. Association name needs to match. You will probably notice that all your fields for photos are gone after that change, this is correct and it means it works. Just add@property.photos.build
in your controller and all should work. - BroiSatse@property.photos.new(params[[:photo][:property_pic]])
@BroiSatse - stringRay2014accepts_nested_attributes_for
you do notbuild
it yourself. You just pass it in with a hash calledothers_attributes
. - Lanny Bose