Rails 4 user_id is nil - ruby-on-rails-4

class User < ActiveRecord::Base
has_one :recovery
end
class Recovery < ActiveRecord::Base
attr_accessor :email
end
class RecoveriesController < ApplicationController
def create
#user=User.find(19)
#recovery=#user.create_recovery!
if #recovery.save
redirect_to :root
end
end
end
After create #recovery.user_id is nil in database
But if I remove the redirect, as here
class RecoveriesController < ApplicationController
def create
#user=User.find(19)
#recovery=#user.create_recovery!
end
end
user_id take its value.
Whats wrong? Rails 4

Here is what should work:
In Your RecoveriesController:
class RecoveriesController < ApplicationController
def create
#user=User.find(19)
#recovery = Recovery.new(user:#user)
if #recovery.save
redirect_to :root
end
end
end
And, I am sure You have it, but that is not listed in Your Recovery model:
belongs_to :user

Related

Getting "Unpermitted parameter: address" even though I included field in my "permit" statement

I’m using Rails 4.2.3. I have this in my user_controller.rb …
def update
#user = current_user
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to url_for(:controller => 'races', :action => 'index') and return
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :dob, :address, :automatic_import)
end
and when my parameters get submitted to “update,”
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"bz24jRzK5qVWolW0oBoQbniiaQi96MeFFmzNjB4kCr0ifUYSsitvQIyod5AWDJd4KS3lrt3mzLiG8F9ef3aJkg==", "user"=>{"first_name"=>"Anthony", "last_name"=>"Alvarado", "dob(2i)"=>"1", "dob(3i)"=>"14", "dob(1i)"=>"1908", "address"=>{"city"=>"chicago"}, "automatic_import"=>"0"}, "state"=>"CT", "country"=>{"country"=>"233"}, "commit"=>"Save", "id"=>"13"}
Unpermitted parameter: address
Why am I getting this unpermitted parameter message when it is included in my “require” statement above? I even have this in my app/models/user.rb file …
class User < ActiveRecord::Base
…
belongs_to :address
There are 2 issues that are linked. (My assumption is that the user has one address, and not that the address has one user.) The model relationship should be:
class User < ActiveRecord::Base
…
has_one :address
accepts_nested_attributes_for :address
The address model:
class Address < ActiveRecord::Base
…
belongs_to :user
This should eliminate the unpermitted parameter error for address.

ActiveModel::ForbiddenAttributesError within Active Admin

I have a model that is only ever created within active admin. I have the following controller setup:
def index
#events = Event.all
end
def new
#event = Event.new
end
def create
#event = Event.new(event_params)
end
private
def event_params
params.require(:event).permit(:venue, :trainer_id, :description, :training_request_id, :title, :date)
end
end
My event model is:
class Event < ActiveRecord::Base
has_one :trainer, inverse_of: :events
belongs_to :training_request, inverse_of: :event
delegate :module, to: :training_request
end
All the fields are there but I cant see why it is throwing this error.
Here is the output from the error:
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"H0sdhO3JsWBb8tYvFm52YvGsVvcnArigaVD+1r5HzL8=",
"event"=>{"training_request_id"=>"3",
"venue"=>"this is a venue",
"description"=>"this is a descripton",
"title"=>"event title",
"date(1i)"=>"2018",
"date(2i)"=>"3",
"date(3i)"=>"5",
"date(4i)"=>"05",
"date(5i)"=>"00",
"commit"=>"Create Event"}
Anyone got any ideas why this is happening?
Its worth mentioning that within rails console it saves fine.
I was missing
controller do
def permitted_params
params.permit event: [:venue, :trainer_id, :description, :training_request_id, :title, :date]
end
end
inside ActiveAdmin.register Event do

Rails upgradation from 3.2.x to 4.0.3 with Ruby 2

models/user.rb
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :login
end
models/post.rb
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
belongs_to :user
attr_accessible :user_id, :description, :title
end
models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
attr_accessible :body, :user_id
end
I have installed 'strong_parameters'. And trying to make out with it. Can any one please guide me for model and controller code for the same.
Remove attr_accessible from models.
And in the controller, lets take the example of PostsController, create a private method post_params where you will define accessible attributes of Post model
class PostsController < ApplicationController
def update
#post = Post.find(params[:id])
if #post.update(post_params)
redirect_to #post, notice: 'Post was successfully updated.'
else
render "edit"
end
end
private
def post_params
params.require(:post).permit(:user_id, :description, :title)
end
end

ruby on rails 4 mass assignment

I have:
a model User for common data such as email, password, first_name, last_name
a model Student for specific data such as faculty_id, etc..
What i want is to have a possibility to modify student's profile, e.g change its faculty and credentials. I found out that accepts_nested_attributes_for should help me with that. So that is what i have:
class User < ActiveRecord::Base
has_one :student
has_one :header
has_one :admin
has_many :progresses, :through => :student
accepts_nested_attributes_for :student
end
class Student < ActiveRecord::Base
belongs_to :user
belongs_to :group
has_one :specialization, through: :group
has_many :progresses
scope :activated, lambda {(where("users.activated = 'off'"))}
self.per_page = 1
end
class Admin::StudentsController < AdminController
before_action :set_user, only: [:show, :edit, :update, :destroy]
def index
#students = Student.joins(:user).joins(:group).paginate(:page => params[:page]).all
end
def show
end
def edit
end
def update
end
private
def set_user
#student = Student.find(params[:id])
#student.build_user
end
end
Form partial
= form_for([:admin,#student]) do |f|
- if #student.errors.any?
#error_explanation
h2
= pluralize(#student.errors.count, "error")
| prohibited this group from being saved:
ul
- #student.errors.full_messages.each do |msg|
li= msg
.field
= f.fields_for :user do |builder|
= builder.label :first_name
br/
= builder.text_field :first_name
.field
= f.label :faculty_id
br/
= f.text_field :faculty_id
.actions
= f.submit
I looked into inspect element in a browser and input for user object is
<input id="student_user_first_name" name="student[user][first_name]" type="text">
which seems correct. But the field is empty. Please tell me where i went wrong? Thank you.
Rails 4 uses Strong Parameters, so you need to whitelist your params in the controller. Here is a good explanation which considers the use of accepts_nested_attribute_for. http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

Carrierwave only upload image when update action when using Rails 4 and nested form

My model:
class Product < ActiveRecord::Base
has_many :product_images, dependent: :destroy
accepts_nested_attributes_for :product_images, :reject_if => lambda { |p| p['image'].blank? }, :allow_destroy => true
end
class ProductImage < ActiveRecord::Base
belongs_to :product
mount_uploader :image, ProductImageUploader
validates_presence_of :image
end
My controller:
def create
#product = Product.new(permitted_params.product)
if #product.save
redirect_to edit_admin_product_path(#product), notice: "success"
else
render :new
end
end
def update
#product = Product.find(params[:id])
if #product.update_attributes(permitted_params.product)
redirect_to edit_admin_product_path(#product), notice: "success"
else
render :edit
end
end
permitted_params:
class PermittedParams < Struct.new(:params)
def product
params.require(:product).permit(*product_attrs)
end
def product_attrs
[:name, :content, :stock, :list_price, :selling_price, :bonus, :is_added,
product_images_attributes: [:id, :image, :_destroy] ]
end
end
And parameters passed:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"eqweq1231sda+3T0131643guXybT75X6NqN1ng=", "product"=>{"name"=>"weqwe", "content"=>"qweq", "product_images_attributes"=>{"0"=>{"image"=>"1069218_513152615405563_1187314087_n.jpg", "_destroy"=>""}}, "stock"=>"", "list_price"=>"", "selling_price"=>"123", "bonus"=>""}, "commit"=>"submit"}
Obviously the image is pass to the params. but when create product it will rollback to alarm the image is empty(validate presence image in my ProductImage model).
If I delete the validation then create the product. I can successfully upload the images in update action. I have totally no idea what's the problem! Please help. Q_Q