Using cocoon gem, but can't save data after first input field - ruby-on-rails

I've tried to implement cocoon in my application, but having trouble saving data after the first input field.
I tried following the example, but no luck.
I'm able to save the first field into database, but nothing happens on the other fields when I add more.
_form.html.erb
<%= simple_form_for(#project) do |f| %>
<%= f.input :project_name %>
<%= f.hidden_field :user_id %>
<div id="tasks">
<%= f.simple_fields_for :tasks do |g| %>
<%= render 'task_fields', :f => g %>
<% end%>
<%= link_to_add_association 'add task', f, :tasks %>
</div>
<%= f.button :submit %>
<% end %>
_task_fields.html.erb
<li class="control-group nested-fields">
<div class="controls">
<%= f.label :task %>
<%= f.text_field :task %>
</div>
<%= link_to_remove_association "remove task", f %>
</li>
Controller
params.require(:project).permit(
:user_id, :project_name,
tasks_attributes: [:id, :task, :_destroy])
And I added:
//= require cocoon
in application.js
Project Model
class Project < ActiveRecord::Base
belongs_to :user
has_many :tasks
accepts_nested_attributes_for :tasks, :reject_if => :all_blank, allow_destroy: true
end
Task Model
class Task < ActiveRecord::Base
belongs_to :project
end
I think I got this correct? I'm able to click on "add task" link and a new field pops up, but those new fields doesn't save.
EDIT from POST in console
Processing by ProjectsController#create as HTML
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"blah",
"project"=>{"project_name"=>"cocoon test",
"tasks_attributes"=>{
"0"=>{"task"=>"fix this!",
"_destroy"=>"false"
}}},
"commit"=>"Create Project"}
(0.2ms) begin transaction
SQL (1.5ms) INSERT INTO "projects" ("project_name", "created_at", "updated_at") VALUES (?, ?, ?) [["project_name", "cocoon test"], ["created_at", "2015-07-15 03:26:09.444377"], ["updated_at", "2015-07-15 03:26:09.444377"]]
SQL (0.4ms) INSERT INTO "tasks" ("task", "project_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["task", "fix this!"], ["project_id", 8], ["created_at", "2015-07-15 03:26:09.450324"], ["updated_at", "2015-07-15 03:26:09.450324"]]
(8.4ms) commit transaction
Redirected to http://localhost:3000/projects/8
Completed 302 Found in 24ms (ActiveRecord: 10.4ms)
EDIT 2 posting project controller methods create and new
def create
#project = Project.new(project_params)
respond_to do |format|
if #project.save
format.html { redirect_to #project, notice: 'Project was successfully created.' }
format.json { render :show, status: :created, location: #project }
else
format.html { render :new }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
def new
#project = Project.new
#project.tasks.build
end

Related

M:N relation error in Rails

i got some error when trying to make relation between Post and Hashtag by m : n
all things fine but when try to save log prints like this
Started POST "/posts" for 127.0.0.1 at 2018-03-05 21:43:00 +0900
Processing by PostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"DxRb+4PAfOsDTCEMx+BcBNKK/LWAH5NxwVh6n7OChtwBL/svUQVEBj7mrWdCYB2BIUHO/Gql9UC6mKLMMoPqEg==", "post"=>{"title"=>"please", "content"=>"please!!!!!", "hashtags_attributes"=>{"0"=>{"title"=>"hash1"}, "1"=>{"title"=>"hash2"}, "2"=>{"title"=>"hash3"}}}, "commit"=>"Create Post"}
Unpermitted parameter: hashtags_attributes
Unpermitted parameters: title, content
Hashtag Load (0.2ms) SELECT "hashtags".* FROM "hashtags" WHERE "hashtags"."title" = ? LIMIT ? [["title", "hash1"], ["LIMIT", 1]]
Unpermitted parameters: title, content
Hashtag Load (0.1ms) SELECT "hashtags".* FROM "hashtags" WHERE "hashtags"."title" = ? LIMIT ? [["title", "hash2"], ["LIMIT", 1]]
Unpermitted parameters: title, content
Hashtag Load (0.1ms) SELECT "hashtags".* FROM "hashtags" WHERE "hashtags"."title" = ? LIMIT ? [["title", "hash3"], ["LIMIT", 1]]
(0.0ms) begin transaction
SQL (0.3ms) INSERT INTO "posts" ("title", "content", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["title", "please"], ["content", "please!!!!!"], ["created_at", "2018-03-05 12:43:00.937624"], ["updated_at", "2018-03-05 12:43:00.937624"]]
SQL (0.1ms) INSERT INTO "hashtags_posts" ("hashtag_id", "post_id") VALUES (?, ?) [["hashtag_id", 1], ["post_id", 2]]
(0.3ms) rollback transaction
Completed 500 Internal Server Error in 12ms (ActiveRecord: 1.4ms)
ActiveModel::MissingAttributeError (can't write unknown attribute `id`):
app/controllers/posts_controller.rb:36:in `block in create'
app/controllers/posts_controller.rb:35:in `create'
Rendering /usr/local/var/rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
Rendering /usr/local/var/rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered /usr/local/var/rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (7.4ms)
Rendering /usr/local/var/rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /usr/local/var/rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms)
Rendering /usr/local/var/rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /usr/local/var/rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.1ms)
Rendered /usr/local/var/rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (124.9ms)
i don't know why title content, and hashtags_attributes are unpermitted parameters. i set them in white list correctly
this is my codes
posts_controller.rb
def create
#post = Post.new(post_params)
3.times do |x|
tag = hashtag_params[:hashtags_attributes]["#{x}"]["title"]
a = Hashtag.find_or_create_by(title: tag)
#post.hashtags << a
end
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: #post }
else
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def hashtag_params
params.require(:post).permit(hashtags_attributes: [:title])
end
this is my post.rb
class Post < ApplicationRecord
has_and_belongs_to_many :hashtags
accepts_nested_attributes_for :hashtags
end
this is my hashtag.rb
class Hashtag < ApplicationRecord
has_and_belongs_to_many :posts
end
At last, my _form.html.erb
<%= form_for(post) do |f| %>
<% if post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %>
<%= f.text_area :content %>
</div>
<div class="field">
<%= f.fields_for :hashtags do |h|%>
<%=h.label :title, "해시태그"%>
<%=h.text_field :title%>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
You only need to specify post_params correctly:
def create
#post = Post.new(post_params)
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: #post }
else
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def post_params
params.require(:post).permit(:title, :content, hashtags_attributes: [:id, :title])
end
You can read more here
And you need to change your migration
class CreateJoinTableHashtagsPosts < ActiveRecord::Migration[5.0]
def change
create_join_table :hashtags, :posts do |t|
t.index :hashtag_id
t.index :post_id
end
end
end
After it you need to run rake db:rollback && rake db:migrate.
Or you can use rake db:drop && rake db:create && rake db:migrate to recreate db from scratch, in this case you lose all existing data

Rails Nested Attributes with has_many through association not creating

I am trying to provide a way to generate a new object ("List") in one model with a new associated object in another ("Item") using a has_many through relationship (through "Groupings"). I was able to get the form working fine but can't figure out what I'm missing in order to finish the creation process correctly.
Rails v. 5.1.2, Ruby v. 2.4.1
lists_controller.rb
def new
#list = current_user.lists.new
3.times { #list.items.build }
end
def create
#list = current_user.lists.new(list_params)
respond_to do |format|
if #list.save
format.html { redirect_to #list, notice: 'List was successfully created.' }
format.json { render :show, status: :created, location: #list }
else
format.html { render :new }
format.json { render json: #list.errors, status: :unprocessable_entity }
end
end
end
private
def set_list
#list = List.find(params[:id])
end
def correct_user
#list = current_user.lists.find_by(id: params[:id])
redirect_to lists_path, notice: "Not authorized to edit this list"
if #list.nil?
end
def list_params
params.require(:list).permit(:title, {
item_attributes: [
:id, :title, :url
]})
end
items_controller.rb
def new
#item = Item.new
end
private
def set_item
#item = Item.find(params[:id])
end
def item_params
params.require(:item).permit(:title, :body, :url, :created,
:list_ids => [])
end
end
list.rb model
has_many :groupings, :dependent => :destroy
has_many :items, :through => :groupings
accepts_nested_attributes_for :items,
reject_if: ->(attrs) { attrs['title'].blank? || attrs['url'].blank? }
item.rb model
has_many :groupings, :dependent => :destroy
has_many :lists, :through => :groupings
validate :has_lists?
accepts_nested_attributes_for :lists
attr_writer :list_titles
after_save :assign_lists
def list_titles
#list_titles || lists.map(&:title).join(' ')
end
private
def assign_lists
if #list_titles
self.lists = #list_titles.split(/\,/).map do |title|
if title[0..0]==" "
title=title.strip
end
title=title.downcase
List.find_or_create_by_title(title)
end
end
end
def has_lists?
errors.add(:base, 'This item needs to be assigned to a list before it can be saved.') if self.lists.blank?
end
grouping.rb model
belongs_to :item
belongs_to :list
accepts_nested_attributes_for :item, :list
Lists Form
<%= form_with(model: list, local: true) do |f| %>
<% if list.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(list.errors.count, "error") %> prohibited this list from being saved:</h2>
<ul>
<% list.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title, id: :list_title %>
</div>
<div>
<p><strong>Items:</strong></p>
<%= f.fields_for :items do |item| %>
<div>
<%= item.label :title %>
<%= item.text_field :title %>
<%= item.label :url %>
<%= item.text_field :url %>
</div>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Sample Console Output
Started POST "/lists" for 127.0.0.1 at 2017-09-19 13:12:53 -0700
Processing by ListsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Y6rszWVUXDIVymuoBkXwvkw1pVbyC6mffiWIZzr7PVd1NT9JJi6rD72k5Fh2qU5Q5tEd0qn6bFYMSJnz2TgjAA==", "list"=>{"title"=>"Websites", "items_attributes"=>{"0"=>{"title"=>"Google", "url"=>"www.google.com"}, "1"=>{"title"=>"Yahoo", "url"=>"www.yahoo.com"}, "2"=>{"title"=>"Bing", "url"=>"www.bing.com"}}}, "commit"=>"Create List"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 2], ["LIMIT", 1]]
Unpermitted parameter: :items_attributes
(0.1ms) BEGIN
SQL (0.9ms) INSERT INTO "lists" ("title", "created_at", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["title", "Websites"], ["created_at", "2017-09-19 20:12:53.458577"], ["updated_at", "2017-09-19 20:12:53.458577"], ["user_id", 2]]
(0.3ms) COMMIT
Redirected to http://localhost:3000/lists/24
Completed 302 Found in 7ms (ActiveRecord: 1.6ms)
I'm still learning, clearly - but after trying all kinds of related hints on this forum I couldn't figure this one out. Thanks for any help!
You're almost there but there is an error being reported in your console logs: Unpermitted parameter: :items_attributes.
Change item_attributes to items_attributes in your list_params:
def list_params
params.require(:list)
.permit(:title, items_attributes: [:id, :title, :url])
end
You have some mistakes in your syntax when you define your params. It should be like this: (items instead item and you don't need {})
def list_params
params.require(:list).permit(:title,
items_attributes: [:id, :title, :url])
end

Rails doesn't update nested attributes

I create an application, which is basically a character creator for an RPG with interactive and dynamic forms. I use Rails 5.0.0.1, and I cannot update my form properly. The base model updates well, but all nested don't.
So, I have
class Character < ApplicationRecord
has_many :attr4characters, autosave: true
accepts_nested_attributes_for :attr4characters, allow_destroy: true
end
and
class Attr4character < ApplicationRecord
belongs_to :character
end
which represent a character and a set of his attributes. Each record in Attr4character is a different attribute.
The Show view is simple:
...
<div class="field">
<%= f.label :description %>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :character_type %>
<%= f.select(:character_type, options_for_select(["Zhong Lung", "Shih", "Hsien", "Garou", "Technocrat"])) %>
</div>
<% f.object.attr4characters.each do |attr| %>
<%= f.fields_for attr do |attr_f| %>
<div class="field">
<%= attr_f.label "Field name" %>
<%= attr_f.text_field :field_name %>
</div>
<div class="field">
<%= attr_f.label "Field value" %>
<%= attr_f.text_field :field_value %>
</div>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
...
And finally my characters_controller:
def update
respond_to do |format|
if #character.update(character_params)
format.html { redirect_to #character, notice: 'Character was successfully updated.' }
format.json { render :show, status: :ok, location: #character }
else
format.html { render :edit }
format.json { render json: #character.errors, status: :unprocessable_entity }
end
end
end
private
def set_character
#character = Character.find(params[:id])
end
def character_params
params.require(:character).permit(:id, :name, :player, :description, :character_type, attr4characters_attributes: [:id, :character_id, :field_name, :field_value])
end
So, I have a form, which correctly display a character and all set of his attributes. When I update a character field (like :description), it is normally updated. When I update any nested field, Rails says that character is successfully updated and nothing changes! I searched with Google, and I found a lot of problems with nested attributes in Rails forms, but none of the recipes worked for me. I even encountered opinions that it is a bug in Rails 4, but I use 5th version...
Please, advice on the topic. Is it a bug really? Or am I doing something wrong? I'm new on Rails, so I don't exclude that possibility. :)
By the way, in the server's log I found that there is warning about attr4characters.
Processing by CharactersController#update as HTML
Parameters: {"utf8"=>"\u2713", "authenticity_token"=>"xeYyIRc13YiOk29v18rFM6Oh5OHRRuPpSKEQuIHE/U4uhANEF7TwMp8mb6hv6L7mUAm5MngAuyFayHcWV/Vvbw==", "character"=>{"name"=>"Ray", "player"=>"111", "description"=>"A Zhong Lung suicider", "character_type"=>"Hsien", "attr4character"=>{"field_name"=>"Gift1", "field_value"=>"Sense Wyrm"}}, "commit"=>"Update Character", "id"=>"3"}
Character Load (0.2ms) SELECT "characters".* FROM "characters" WHERE "characters"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
Unpermitted parameter: attr4character
(0.1ms) begin transaction
SQL (0.9ms) UPDATE "characters" SET "character_type" = ?, "updated_at" = ? WHERE "characters"."id" = ? [["character_type", "Hsien"], ["updated_at", 2016-09-13 14:39:10 UTC], ["id", 3]]
(24.3ms) commit transaction
But attr4characters are permitted in the characters_controller...
The warning is telling you that it is ignoring all the attr4character attributes. Your permit code is correct as is your model, but your view doesn't match them. You should be doing
f.fields_for :attr4characters do |attr_f|
...
end
And let rails handle iterating over the association. This will also ensure that attributes are named correctly (so they will be allowed through by your whitelist)

Rails Paperclip inserting instead of updating

I created a simple application that has a Product and an Image model. Product has_many Images and Images has an attached file attribute (paperclip).
I created a simple_form for creating/editing Products and it works fine on creation. However, when editing a Product that has N images, rails inserts more N files - empty files.
I have set up a Simple Form custom input that tests if the image attachment exists in which case instead of rendering the builders input, it only renders an image_tag().
I see the html generated and it show something strange, a hidden tag:
<input id="product_images_attributes_0_id" name="product[images_attributes][0][id]" type="hidden" value="14">
And in the rails server console I see:
Processing by ProductsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"asdfasdfaasdf=", "product"=>{"reference"=>"Y1112CYL.E2", "images_attributes"=>{"0"=>{"id"=>"14"}}}, "commit"=>"Update Product", "id"=>"20"}
Product Load (0.6ms) SELECT "products".* FROM "products" WHERE "products"."id" = $1 LIMIT 1 [["id", "20"]]
Unpermitted parameters: id
(0.2ms) BEGIN
SQL (1.0ms) INSERT INTO "images" ("created_at", "imageable_id", "imageable_type", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Tue, 18 Feb 2014 05:05:13 UTC +00:00], ["imageable_id", 20], ["imageable_type", "Product"], ["updated_at", Tue, 18 Feb 2014 05:05:13 UTC +00:00]]
(0.6ms) COMMIT
Here is the code to my implementation. If someone could help I would be very happy! Please pardon me if I left out any import part of the code, I will gladly edit the question to include it.
_form.html.erb
<%= simple_form_for(#product) do |f| %>
<%= f.error_notification %>
<div class="inputs">
<%= f.input :reference %>
<h3>Images</h3>
<div id='images'>
<%= f.simple_fields_for :images do |image| %>
<%= render 'image_fields', :f => image %>
<% end %>
<div class='links'>
<%= link_to_add_association 'New image', f, :images %>
</div>
</div>
</div>
<div class="actions">
<%= f.button :submit %>
</div>
<%end%>
_image_fields.html.erb
<%= content_tag :div, class: "nested-fields images-fields" do %>
<%= content_tag :div, id: "new-image" do %>
<% if f.object.photo.exists? %>
<% f.template.image_tag(f.object.photo.url(:thumb)) %>
<% else %>
<% f.input :photo, :as => :photo %>
<% end %>
<% end %>
<% end %>
app/inputs/photo_input.erb
class PhotoInput < SimpleForm::Inputs::FileInput
def input
out = '' # the output string we're going to build
# check if there's an uploaded file (eg: edit mode or form not saved)
if object.send("#{attribute_name}?")
# append preview image to output
# <%= image_tag #user.avatar.url(:thumb), :class => 'thumbnail', id: 'avatar' %>
out << template.image_tag(object.send(attribute_name).url(:thumb), :class => 'thumbnail', id: 'photo')
else
# append file input. it will work accordingly with your simple_form wrappers
(out << #builder.file_field(attribute_name, input_html_options)).html_safe
end
end
end
ProductsController#update
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
For posterity, #omarvelous' comment seems to have solved it:
I added the reject if all blank to my accepts_nested_attributes_for
accepts_nested_attributes_for :images, :allow_destroy => true, :reject_if => :all_blank
Edit:
It turns out there is an issue with this solution. When reject_if => :all_blank is it stops the destroy from working properly. See this post that shows a workaround -- that I did not manage to get to work.

Unpermitted parameters , nested forms - Ruby On Rails

I have follow Michael Hartl's tutorial and now I want to add photos to microposts. But when I submit microposts, the image isn't saved in the database and in the dvlpmt log I can read unpermitted parameters :image
I have look in other posts and did what they advice but it doesn't work for me.
MODELS
micropost.rb
class Micropost < ActiveRecord::Base
belongs_to :user
has_one :photo
default_scope -> { order('created_at DESC') }
validates :content, presence: true, length: { maximum: 140 }
validates :user_id, presence: true
end
photo.rb
class Photo < ActiveRecord::Base
belongs_to :micropost
has_attached_file :image
end
CONTROLLERS
photos_controller.rb
class PhotosController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy, :index]
def create
#photo = Photo.new(photo_params)
respond_to do |format|
if #photo.save
format.html { redirect_to #photo, notice: 'Photo was successfully created.' }
format.json { render action: 'static_pages/home', status: :created, location: #photo }
else
format.html { render action: 'static_pages/home' }
format.json { render json: #photo.errors, status: :unprocessable_entity }
end
end
end
private
def photo_params
params.require(:photo).permit(:image)
end
end
microposts_controller.rb
class MicropostsController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy]
def create
#micropost = current_user.microposts.build(micropost_params)
if #micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
#feed_items = []
render 'static_pages/home'
end
end
private
def micropost_params
params.require(:micropost).permit(:content, photo_attributes: [:photo_id, :image])
end
end
VIEWS
_micropost_form.html.erb
I dont know how to construct well this form, I've tried a lot of different formulations
<%= form_for(#micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Compose new micropost..." %>
</div>
<%= f.fields_for :image, :html => { :multipart => true } do |builder| %>
<%= f.file_field :image, :f => builder %>
<% end %>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
And when I want to submit my form, it is ok, but the column "photo_id" is empty for the table micropost. And photo isn't saved in the database.
Server log
Started POST "/microposts" for 127.0.0.1 at 2013-11-27 15:06:06 +0100
Processing by MicropostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"<my_private_token>", "micropost"=>{"content"=>"Hello world", "image"=>#<ActionDispatch::Http::UploadedFile:0x00000003401a48 #tempfile=#<Tempfile:/tmp/RackMultipart20131127-4010-1r6qt80>, #original_filename="paint.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"micropost[image]\"; filename=\"paint.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Post"}
[1m[36mUser Load (0.2ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."remember_token" = '342df8f039f7f40698b3691f77d2539dc8b9c101' LIMIT 1[0m
Unpermitted parameters: image
[1m[35m (0.1ms)[0m begin transaction
[1m[36mSQL (0.4ms)[0m [1mINSERT INTO "microposts" ("content", "created_at", "updated_at", "user_id") VALUES (?, ?, ?, ?)[0m [["content", "Hello world"], ["created_at", Wed, 27 Nov 2013 14:06:06 UTC +00:00], ["updated_at", Wed, 27 Nov 2013 14:06:06 UTC +00:00], ["user_id", 101]]
[1m[35m (145.1ms)[0m commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 153ms (ActiveRecord: 145.7ms)
I am completely stuck right now, thank you if you can find something that can help me where to find the solution!!!
You need to use accepts_nested_attributes_for in your Micropost class.
class Micropost < ActiveRecord::Base
belongs_to :user
has_one :photo
accepts_nested_attributes_for :photo
default_scope -> { order('created_at DESC') }
validates :content, presence: true, length: { maximum: 140 }
validates :user_id, presence: true
end
It also looks like your form was associating the image with your micropost, not with the micropost's photo. Take a look at the Ruby docs for fields_for. Can you try changing part of your form to this?
<%= f.fields_for :photo, :html => { :multipart => true } do |photo_fields| %>
<%= photo_fields.file_field :image %>
<% end %>
If you do this, you'll need to make sure you call #micropost.build_photo in the controller action that renders the view.
I don't think you need to list photo_id in your strong parameters in microposts_controller.rb. That should get set once the records save to the database.
You can also read the Rails Guides on building complex forms. The guide talks about how to set up your model, view, and controller to handle nested attributes. Their description of strong parameters may be helpful to check out, if you haven't yet.

Resources