Rails: Polymorphic assosiation and accepts_nested_attributes - ruby-on-rails

The attachment won't save. What I am missing here?
In my application I have a project ,for each project user can upload many assets. The Upload is done by carrier wave.
here are the models
class Project < ActiveRecord::Base
has_many :assets,:as => :assetable,dependent: :destroy
accepts_nested_attributes_for :assets, :allow_destroy => true
end
class Asset < ActiveRecord::Base
belongs_to :project
belongs_to :user
belongs_to :assetable, :polymorphic => true
mount_uploader :attachment, AttachmentUploader #carrierwave
validates :attachment, presence: true
validates :project_id, presence: true
end
and these are the actions in my project_controller
def new
#project = Project.new
#asset = #project.assets.build
end
def create
#project = Project.new(project_params)
#project.assets.build
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
def project_params
params.require(:project).permit(:user_id, :summary, :start_date,assets_attributes: [:id, :project_id, :attachment,:user_id] )
end
this is how the form looks like
<%= form_for #project,:html => {:multipart => true } do |f| %>
<% if #project.errors.any? %>
<div id="error_explanation">
</div>
<% end %>
<%= f.fields_for :assets do |p| %>
<div class="field">
<%= p.label :attachment %><br>
<%= p.file_field :attachment,name: "assets[attachment][]" %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

schema.rb
create_table "assets", force: true do |t|
t.string "assetable_id"
t.string "assetable_type"
t.string "attachment"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "projects", force: true do |t|
t.string "user_id"
t.string "summary"
t.datetime "created_at"
t.datetime "updated_at"
end
projects/_form.html.erb
<%= form_for #project, :html => {:multipart => true } do |f| %>
<% if #project.errors.any? %>
<div id="error_explanation">
<%= #project.errors.inspect %>
</div>
<% end %>
<%= f.label :summary %>
<%= f.text_field :summary %>
<%= f.fields_for :assets do |p| %>
<div class="field">
<%= p.label :attachment %><br>
<%= p.file_field :attachment %>
<%= p.hidden_field :assetable_id %>
<%= p.hidden_field :assetable_type %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
projects_controller.rb
# GET /projects/new
def new
#project = Project.new
#project.assets.build
end
# POST /projects
# POST /projects.json
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
private
# Never trust parameters from the scary internet, only allow the white list through.
def project_params
params.require(:project).permit(:user_id, :summary, :start_date, assets_attributes: [:id, :assetable_id, :assetable_type, :attachment, :user_id] )
end
project.rb
class Project < ActiveRecord::Base
has_many :assets, :as => :assetable, dependent: :destroy
accepts_nested_attributes_for :assets, :allow_destroy => true
end
asset.rb
class Asset < ActiveRecord::Base
belongs_to :project
belongs_to :assetable, :polymorphic => true
mount_uploader :attachment, AttachmentUploader #carrierwave
validates :attachment, presence: true
validates :assetable_type, presence: true
end
Aside
Since you based this question off a previous question you asked I'll just mention: You only want to use a polymorphic association if you intend instances of your asset class to belong to different types of classes (ie. things other than a project).

Related

Could not save nested form in rails 5.1

I used nested_form gem and I am trying to build a form which has fields from two tables(Project, Question).
My model:
class Project < ApplicationRecord
has_many :questions
accepts_nested_attributes_for :questions
end
class Question < ApplicationRecord
belongs_to :project
end
My controller:
class ProjectsController < ApplicationController
layout 'application'
def index
#projects = Project.all
end
def show
#project = Project.find(params[:id])
end
def new
#project = Project.new
#questions = #project.questions.build
end
def create
#project = Project.new(project_params)
#project.save
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
private
def project_params
params.require(:project).permit(:name, question_attributes: [:id, :content, :_delete])
end
end
My view:
<%= nested_form_for(#project) do |f| %>
<% if #project.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(#project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% #project.errors.full_messages.each do |message| %>
<li>
<%= message %>
</li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<%= f.fields_for :questions do |builder| %>
<%= render "question_fields", :ff => builder %>
<% end %>
<p>
<%= f.link_to_add "Add a questions",:questions %>
</p>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And my schema file :
create_table "projects", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "questions", force: :cascade do |t|
t.integer "project_id"
t.string "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["project_id"], name: "index_questions_on_project_id", using: :btree
end
And _question_fields file is :
<p>
<%= ff.label :content, "Question" %>
<%= ff.text_area :content%>
<%= ff.link_to_remove "Remove this task"%>
</p>
Table Project will be saved but the table Question could not be saved.Why?
After change this line of code
def project_params
params.require(:project).permit(:name, questions_attributes: [:id, :content, :_delete])
end
I get the following error:
1 error prohibited this project from being saved:
Questions project must exist
I applied the change too ,but this time nothing could not be saved.
def project_params
params.require(:project).permit(:name, questions_attributes: [:id, :content, :project_id, :_delete])
end
The issue is with the project_params. As you have has_many :questions, the question_attributes should be changed to questions_attributes
def project_params
params.require(:project).permit(:name, questions_attributes: [:id, :content, :_delete])
end
Update:
Questions project must exist
Either permit project_id in questions_attributes
def project_params
params.require(:project).permit(:name, questions_attributes: [:id, :content, :project_id, :_delete])
end
or set optional: true on the association
class Question < ApplicationRecord
belongs_to :project, optional: true
end

Cannot access associated model attributes within a form

I am trying to build a form for a has_many :through relationship. The Problem is, that I can access the attributes from the join table (:through) in the form, but not the other table.
My models look like this:
class Recipe < ActiveRecord::Base
has_many :quantities
has_many :ingredients, through: :quantities
accepts_nested_attributes_for :quantities
end
class Quantity < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
class Ingredient < ActiveRecord::Base
has_many :quantities
has_many :recipes, through: :quantities
end
My Form:
<%= form_for(#recipe) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="quantities">
<%= f.fields_for :quantities do |builder| %>
<%= render 'quantity_fields', :f => builder%>
<% end %>
<%= link_to_add_association 'Add', f, :quantities %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And the quantity_fields partial:
<p>
<%= f.label :value, "Value" %>
<%= f.text_field :value %>
<%= f.label :unit, "Unit" %>
<%= f.text_field :unit %>
<%= f.text_field :ingredient %>
<%= f.fields_for :ingredient do |builder|%>
<%= builder.label :name, "Ingredient"%>
<%= builder.text_field :name %>
<% end %>
</p>
The fields for the quantities attributes are correct, but the text field for the ingredient name (within the quantity_fields partial) stays empty.
On the Rails console on the other hand I can easily use the ingredient method on a quantity object and get a result.
I try to find a solution to this since a while now, and it becomes really frustrating to me. I am sure this is a standard task and I am just missing a small part. Can anyone help me?
Edit:
Also when I change my recipe form to directly render the ingredients, it doesn't work. The text fields remain empty.
<%= form_for(#recipe) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="ingredients">
<%= f.fields_for :ingredients do |builder| %>
<p>
<%= builder.label :name, "Name" %>
<%= builder.text_field :name %>
<%= builder.label :description, "Description" %>
<%= builder.text_field :description %>
</p>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Edit 2:
The recipes controller:
class RecipesController < ApplicationController
before_action :set_recipe, only: [:show, :edit, :update, :destroy]
# GET /recipes
# GET /recipes.json
def index
#recipes = Recipe.all
end
# GET /recipes/1
# GET /recipes/1.json
def show
end
# GET /recipes/new
def new
#recipe = Recipe.new
end
# GET /recipes/1/edit
def edit
end
# POST /recipes
# POST /recipes.json
def create
#recipe = Recipe.new(recipe_params)
respond_to do |format|
if #recipe.save
format.html { redirect_to #recipe, notice: 'Recipe was successfully created.' }
format.json { render :show, status: :created, location: #recipe }
else
format.html { render :new }
format.json { render json: #recipe.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /recipes/1
# PATCH/PUT /recipes/1.json
def update
respond_to do |format|
if #recipe.update(recipe_params)
format.html { redirect_to #recipe, notice: 'Recipe was successfully updated.' }
format.json { render :show, status: :ok, location: #recipe }
else
format.html { render :edit }
format.json { render json: #recipe.errors, status: :unprocessable_entity }
end
end
end
# DELETE /recipes/1
# DELETE /recipes/1.json
def destroy
#recipe.destroy
respond_to do |format|
format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_recipe
#recipe = Recipe.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def recipe_params
params.require(:recipe).permit(:title, :description, quantities_attributes: [:value, :unit, :recipe, :ingredient, :_destroy])
end
end
When utilizing a has_many :through association in that way, you can set up your models like this:
class Recipe < ActiveRecord::Base
has_many :quantities
has_many :ingredients, inverse_of: :recipes
accepts_nested_attributes_for :quantities
end
class Quantity < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
accepts_nested_attributes_for :ingredients
end
class Ingredient < ActiveRecord::Base
has_many :quantities
has_many :recipes, inverse_of: :ingredients
end
This article covers nested attributes with has_many :through associations in a similar context. Hope this helps!

Rails 4 nested attributes multiple records when updating

I'm stuck and I don't know why it is not working right.
I have a model product which has many tags.
When I update the product rails update properly the products attributes but is creating another tag record instead of just updating it.
here is my code:
View form:
<%= form_for ([#product.user, #product]), id: 'edit_form' do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.fields_for :tags do |t| %>
<%= t.label :name %>
<%= t.text_field :name %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
product model:
class Product < ActiveRecord::Base
belongs_to :user, :foreign_key => "user_id"
has_many :tags, :dependent => :destroy
accepts_nested_attributes_for :tags, reject_if: :all_blank, allow_destroy: true, :update_only => true
end
tags model:
class Tag < ActiveRecord::Base
belongs_to :product, :foreign_key => "product_id"
# before_save { name.downcase! }
end
product controller:
def edit
user = User.find(params[:user_id])
#product = user.products.find(params[:id])
#tags = #product.tags.all
respond_to do |format|
format.html
format.js
end
end
def update
user = User.find(params[:user_id])
#product = user.products.find(params[:id])
#tags = #product.tags.all
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to([#product.user, #product], :notice => 'Product successfully updated.') }
else
format.html { render :action => "edit" }
end
end
end
def product_params
params.require(:product).permit(:name, :description, tags_attributes: :name)
end
You have to pass the tag id in the permit params in your controller
def product_params
params.require(:product).permit(:name, :description, tags_attributes: [:id,:name])
end

RoR: Carrierwave Not Working/Saving to Database

This is my hacked together attempt at getting Carrierwave to work right from watching Railscast. I have a Post Project page where users enter in details for a project. They can also upload a file to this page, and submit the project. So I am using a nested_form_for on the page.
new_step_3.html.erb
<%= nested_form_for #project, :html => {:multipart => true} do |f| %>
<%= f.text_field :title %>
<%= f.text_field :description %>
<%= f.fields_for :document do |attachment_form| %>
<%= attachment_form.file_field :title %>
<% end %>
<%= f.text_field :skills %>
<%= f.submit 'Post Project' %>
<% end %>
project.rb model
attr_accessible :category, :title, :budget, :end_date, :description, :skills, :document, :days_lasting, :documents_attributes
belongs_to :user
has_many :posts
has_many :documents, :as => :attachable
validates_presence_of :category, :title, :description, :skills
accepts_nested_attributes_for :documents
document.rb model
attr_accessible :project_id, :title, :document
belongs_to :user
belongs_to :project
has_many :posts
mount_uploader :document, DocumentUploader
projects_controller.rb
def create
#project = current_user.projects.build(params[:project])
respond_to do |format|
if #project.save
format.html { redirect_to project_step_4_path(:start => #project.id), notice: 'Project was successfully created.' }
format.json { render json: #project, status: :created, location: #project }
else
format.html { render action: "new" }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
Right now, when I try to submit the form, it will say unknown attribute: document
app/controllers/projects_controller.rb:85:in `create'
Running the command in Rails console works Document.create!(:document => File.new("test.jpg"))
I think it should be
<%= f.fields_for :documents do |attachment_form| %>
<%= attachment_form.file_field :title %>
<% end %>
with fields_for :documents
That's why it's not finding the document attribute. Your form probably sends a hash like that:
{
:project => {
:title => "blabla",
:document => {...}
}
}
and it doesnt know what to do with the document.
Now your nested documents will be in :documents => {}, and with the accepts_nested_attributes_for, it should work.
You have to build a document for this project in the controller:
#project.documents.build

Rails: Can't get fields_for to work inside a nested resource

I'm trying to add a fields_for attribute to a nested rails form. Any time I try to create a new object, it returns
Message(#58819400) expected, got
Array(#18903800) ...
app/controllers/discussions_controller.rb:53:in
`create'
If I try to access nested fields_for from forms based on non-nested resources (aka "form_for #parent" instead of "form_for [#parent, #child]" it works fine. Code below - any help with this really appreciated.
Controller:
# GET /discussions/new
# GET /discussions/new.xml
def new
#forum = Forum.find(params[:forum_id])
#discussion = Discussion.new
#discussion.messages.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #discussion }
end
end
def create
#forum = Forum.find_by_id(params[:forum_id])
#discussion = #forum.discussions.new(params[:discussion])
#discussion.user = current_user
respond_to do |format|
if #discussion.save
format.html { redirect_to([#forum, #discussion], :notice => 'Discussion was successfu#ly created.') }
format.xml { render :xml => [#forum, #discussion], :status => :created, :location => #discussion }
else
format.html { render :action => "new" }
format.xml { render :xml => #discussion.errors, :status => :unprocessable_entity }
end
end
end
Models:
class Forum < ActiveRecord::Base
belongs_to :user
has_many :discussions, :dependent => :destroy
validates :title, :presence => true
accepts_nested_attributes_for :discussions, :allow_destroy => true
end
class Discussion < ActiveRecord::Base
belongs_to :user
belongs_to :forum
has_many :messages, :dependent => :destroy
validates :title, :presence => true
end
class Message < ActiveRecord::Base
belongs_to :user
validates :user, :presence => true
validates :content, :presence => true
end
The view:
<%= form_for [#forum, #discussion] do |f| %>
<% if #discussion.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#discussion.errors.count, "error") %> prohibited this discussion from being saved:</h2>
<ul>
<% #discussion.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<%= f.fields_for :messages do |builder| %>
<%= builder.label :content, "Message" %>
<%= builder.text_area :content, :rows => 10 %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And finally, the routing:
resources :forums do
resources :discussions do
resources :messages
end
end
Any help with this really appreciated - I'm completely stumped.
Arghhh - really sorry folks...I just realised I'd forgot the accepts_nested_attributes_for in the discussions model, & consequently forums could access discussions, but discussions couldn't get down to messages.
Thanks anyhow.

Resources