Rectangle 27 39

Your problem is probably not in your controller, but your model: Check to see your attributes are accessible with the follow tag

attr_accessible :title, :price, :description

Rails 4 does do it a little different from what I understand, this previous SO answer provided some good links: How is attr_accessible used in Rails 4?

You need to use attr_accessible/Strong Params whenever you're accessing things from the database.

Oh to be young, and not realize Rails 4 uses Strong Params. I understand the OP has already solved his original problem, but I'm going to correct this so it could actually be used as the right answer.

This would be a controller level issue, as Rails 4 requires you to whitelist attributes in the controller.

Ad.create(params[:ad].require(:ad).permit(:title, :price, :description))

Most of the time you'll be permitting the same params in the create and update action, so it's best to move it into its own method within the controller.

Ad.create(ad_params)
def ad_params
  params.require(:ad).permit(:title, :price, :description)
end

As OP pointed out in his comment, the permitted_params method he implemented was not being called from the permit.

my problem was passing wrong value to new method in create action, solution was to pass ad_params to it

This probably shouldn't be marked as the answer.

This is not the answer.

I agree, this doesn't help anything I experience the same issue and that answer didn't help anything I still get the ActiveModel::ForbiddenAttributesError in PostsController error.

@mer Posted an update a few weeks to make it not wrong, see if that works for you.

rails 4 ActiveModel::ForbiddenAttributesError - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 20

If you prefer attr_accessible, you could use it in Rails 4 too. You should install it like gem:

gem 'protected_attributes'

after that you could use attr_accessible in you models like in Rails 3

Also, and i think that is the best way- using form objects for dealing with mass assignment, and saving nested objects, and you can also use protected_attributes gem that way

class NestedForm
   include  ActiveModel::MassAssignmentSecurity
   attr_accessible :name,
                   :telephone, as: :create_params
   def create_objects(params)
      SomeModel.new(sanitized_params(params, :create_params))
   end
end

When you use 'strong parameters' you filter parameters in controller layer, and i don't think that this is best idea for all applications. For me the best way to filter parameters is to use additional layer. And we can use 'protected_attributes' gem to write this layer

How is attr_accessible used in Rails 4? - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 20

If you prefer attr_accessible, you could use it in Rails 4 too. You should install it like gem:

gem 'protected_attributes'

after that you could use attr_accessible in you models like in Rails 3

Also, and i think that is the best way- using form objects for dealing with mass assignment, and saving nested objects, and you can also use protected_attributes gem that way

class NestedForm
   include  ActiveModel::MassAssignmentSecurity
   attr_accessible :name,
                   :telephone, as: :create_params
   def create_objects(params)
      SomeModel.new(sanitized_params(params, :create_params))
   end
end

When you use 'strong parameters' you filter parameters in controller layer, and i don't think that this is best idea for all applications. For me the best way to filter parameters is to use additional layer. And we can use 'protected_attributes' gem to write this layer

How is attr_accessible used in Rails 4? - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 425

Dealing with accepts_nested_attributes_for

Protecting attributes is now done in the controller. This is an example:

class PeopleController < ApplicationController
  def create
    Person.create(person_params)
  end

  private

  def person_params
    params.require(:person).permit(:name, :age)
  end
end
attr_accessible
accepts_nested_attribute_for
class Person
  has_many :pets
  accepts_nested_attributes_for :pets
end

class PeopleController < ApplicationController
  def create
    Person.create(person_params)
  end

  # ...

  private

  def person_params
    params.require(:person).permit(:name, :age, pets_attributes: [:name, :category])
  end
end

Keywords are self-explanatory, but just in case, you can find more information about strong parameters in the Rails Action Controller guide.

Note: If you still want to use attr_accessible, you need to add protected_attributes to your Gemfile. Otherwise, you will be faced with a RuntimeError.

RuntimeError in MicropostsController#index 'attr_accessible' is extracted out of Rails into a gem. Please use new recommended protection model for params(strong_parameters) or add 'protected_attributes' to your Gemfile to use old one.

Great explanation. It seems like in practice, though, this moves Rails away from fat model, thin controller, etc, and towards thin models, and really bloated controllers. You have to write all this stuff for every instance, it doesn't read nicely, and nesting seems to be a pain. The old attr_accessible/attr_accessor in the model system wasn't broken, and didn't need to be fixed. One blog post got too popular in this case.

So gimmiky & frequently changing apis, coupled with newfound pedantics waste many developer hours in yet another painful Rails upgrade :-(

How is attr_accessible used in Rails 4? - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 427

Dealing with accepts_nested_attributes_for

Protecting attributes is now done in the controller. This is an example:

class PeopleController < ApplicationController
  def create
    Person.create(person_params)
  end

  private

  def person_params
    params.require(:person).permit(:name, :age)
  end
end
attr_accessible
accepts_nested_attribute_for
class Person
  has_many :pets
  accepts_nested_attributes_for :pets
end

class PeopleController < ApplicationController
  def create
    Person.create(person_params)
  end

  # ...

  private

  def person_params
    params.require(:person).permit(:name, :age, pets_attributes: [:name, :category])
  end
end

Keywords are self-explanatory, but just in case, you can find more information about strong parameters in the Rails Action Controller guide.

Note: If you still want to use attr_accessible, you need to add protected_attributes to your Gemfile. Otherwise, you will be faced with a RuntimeError.

RuntimeError in MicropostsController#index 'attr_accessible' is extracted out of Rails into a gem. Please use new recommended protection model for params(strong_parameters) or add 'protected_attributes' to your Gemfile to use old one.

Great explanation. It seems like in practice, though, this moves Rails away from fat model, thin controller, etc, and towards thin models, and really bloated controllers. You have to write all this stuff for every instance, it doesn't read nicely, and nesting seems to be a pain. The old attr_accessible/attr_accessor in the model system wasn't broken, and didn't need to be fixed. One blog post got too popular in this case.

So gimmiky & frequently changing apis, coupled with newfound pedantics waste many developer hours in yet another painful Rails upgrade :-(

How is attr_accessible used in Rails 4? - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 4

params.require(:person).permit(:name, :age)

where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method

How is attr_accessible used in Rails 4? - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 4

params.require(:person).permit(:name, :age)

where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method

How is attr_accessible used in Rails 4? - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 1

1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:

gem 'devise', '3.0.0.rc'

2) Add the old functionality of attr_accessible again to rails 4.0

attr_accessible
gem 'protected_attributes'
$ bundle

How is attr_accessible used in Rails 4? - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 1

1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:

gem 'devise', '3.0.0.rc'

2) Add the old functionality of attr_accessible again to rails 4.0

attr_accessible
gem 'protected_attributes'
$ bundle

How is attr_accessible used in Rails 4? - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 12

Using virtual attributes in Rails 4 pretty much the same as with attr_accessible. You just have to add your virtual attribute to the permitted params in your controller (instead of attr_accessible), then add the getter and setter methods as usual in your model.

# your_controller.rb
private

def your_model_params
  params.require(:your_model_name).permit(:tags_list)
end

But it does not work with #new and #create at the moment, which makes it pretty much useless, because you would have to write your_virtual_attr=:something separately all the time. Anyone else noticed this and has a clue on how to handle it?

I also noticed that calling Tag.new(tags_list: [1, 2]) doesn't fire the tags_list=() virtual attribute.. is this a bug?

before_action :your_model_params
exlcude: , except: [:action1, :action2, etc.]

Virtual attributes in rails 4 - Stack Overflow

ruby-on-rails ruby-on-rails-4 attr-accessor virtual-attribute
Rectangle 27 69

attr_accessor is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or model, if you wanted, but mostly in your View.

attr_accessible allows you to list all the columns you want to allow Mass Assignment, as andy eluded to above. The opposite of this is attr_protected which means this field i do NOT want anyone to be allowed to Mass Assign to. More then likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.

This is a very good explanation of the differences between the two, but it doesn't the question: what happens when you use them both on the same field (or what happens with persistence). For that, se my summary answer below.

ruby on rails - Using attr_accessor and attr_accessible on the same fi...

ruby-on-rails field attr-accessible attr-accessor
Rectangle 27 69

attr_accessor is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or model, if you wanted, but mostly in your View.

attr_accessible allows you to list all the columns you want to allow Mass Assignment, as andy eluded to above. The opposite of this is attr_protected which means this field i do NOT want anyone to be allowed to Mass Assign to. More then likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.

This is a very good explanation of the differences between the two, but it doesn't the question: what happens when you use them both on the same field (or what happens with persistence). For that, se my summary answer below.

ruby on rails - Using attr_accessor and attr_accessible on the same fi...

ruby-on-rails field attr-accessible attr-accessor
Rectangle 27 202

how do you specify a column name for the foreign key instead the auto generated name?

@jwill you can use polymorphic: user:references{polymorphic}.

@PauloFidalgo Can you explain a bit about how to do that? may be some guide of links? (talking about polymorphic)

activerecord - Rails 3 migrations: Adding reference column? - Stack Ov...

ruby-on-rails activerecord migration
Rectangle 27 202

how do you specify a column name for the foreign key instead the auto generated name?

@jwill you can use polymorphic: user:references{polymorphic}.

@PauloFidalgo Can you explain a bit about how to do that? may be some guide of links? (talking about polymorphic)

activerecord - Rails 3 migrations: Adding reference column? - Stack Ov...

ruby-on-rails activerecord migration
Rectangle 27 7

Using Devise with Capybara

Like others have already said, you're including the Devise::TestHelpers. That's for testing controllers. If you'd still like to automatically login a test user in your integration tests, check out the official Devise Instructions on using it with Capybara.

Basically, what you need to do is first enable Warden's test mode:

include Warden::Test::Helpers
Warden.test_mode!
user = FactoryGirl.create(:user)
login_as(user, scope: :user)
# spec/features/survey_spec.rb
require 'rails_helper'

feature 'survey app' do
    include Warden::Test::Helpers

    let(:user)   { create(:user) }
    let(:survey) { create(:survey_with_questions) }

    before do
        # Sign the User in
        Warden.test_mode!
        login_as(user, scope: user)
    end

    it 'renders the survey' do
        visit survey_show_path(survey)
        expect(page).to have_content(survey.title)
    end
end

Thank you, works fine, but I recommend put it on rails_helper to follow a DRY approach better.

ruby on rails 4 - "undefined method `env' for nil:NilClass" in 'setup_...

ruby-on-rails-4 rspec devise capybara factory-bot
Rectangle 27 10

Some times there is a chance where rails server not closed properly. You can find process used by rails

user     12609  9.8  0.5  66456 45480 pts/0    Sl+  21:06   0:02 /home/user/.rvm/rubies/ruby-2.2.0-preview1/bin/ruby bin/rails s

Here process_id 12609 is used by your rails server.

You can kill it easily by command

This has become "ps aux | grep ruby" for me. Maybe from the switch from webrick to puma

Rails server says port already used, how to kill that process? - Stack...

ruby-on-rails
Rectangle 27 52

attr_accessor is a core feature of Ruby and is used to generate instance variables with getter and setter methods. Its use is never required in basic Ruby (it's a convenience).

In the case of ActiveRecord models, getters and setters are already generated by ActiveRecord for your data columns. attr_accessor is not needed or desirable.

If you have additional instance data you don't need to persist (i.e. it's not a database column), you could then use attr_accessor to save yourself a few lines of code.

The similarly-named attr_accessible which is frequently seen in Rails code and confused with attr_accessor is a deprecated method of controlling mass assignment within ActiveRecord models. Rails 4 doesn't support it out of the box; it has been replaced by Strong Parameters, which allows more granular control.

ruby - Why is attr_accessor necessary in Rails? - Stack Overflow

ruby-on-rails ruby
Rectangle 27 321

I have been reading about using model concerns to skin-nize fat models as well as DRY up your model codes. Here is an explanation with examples:

Consider a Article model, a Event model and a Comment model. An article or an event has many comments. A comment belongs to either Article or Event.

As we can notice, there is a significant piece of code common to both Event and Article. Using concerns we can extract this common code in a separate module Commentable.

For this create a commentable.rb file in app/models/concerns.

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end
class Article < ActiveRecord::Base
  include Commentable
end

Consider a Event model. A event has many attenders and comments.

Typically, the event model might look like this

class Event < ActiveRecord::Base   
  has_many :comments
  has_many :attenders


  def find_first_comment
    # for the given article/event returns the first comment
  end

  def find_comments_with_word(word)
    # for the given event returns an array of comments which contain the given word
  end 

  def self.least_commented
    # finds the event which has the least number of comments
  end

  def self.most_attended
    # returns the event with most number of attendes
  end

  def has_attendee(attendee_id)
    # returns true if the event has the mentioned attendee
  end
end

Models with many associations and otherwise have tendency to accumulate more and more code and become unmanageable. Concerns provide a way to skin-nize fat modules making them more modularized and easy to understand.

The above model can be refactored using concerns as below: Create a attendable.rb and commentable.rb file in app/models/concerns/event folder

module Attendable
  extend ActiveSupport::Concern

  included do 
    has_many :attenders
  end

  def has_attender(attender_id)
    # returns true if the event has the mentioned attendee
  end

  module ClassMethods
    def most_attended
      # returns the event with most number of attendes
    end
  end
end
module Commentable
  extend ActiveSupport::Concern

  included do 
    has_many :comments
  end

  def find_first_comment
    # for the given article/event returns the first comment
  end

  def find_comments_with_word(word)
    # for the given event returns an array of comments which contain the given word
  end

  module ClassMethods
    def least_commented
      # finds the event which has the least number of comments
    end
  end
end
class Event < ActiveRecord::Base
  include Commentable
  include Attendable
end

* While using concerns its advisable to go for 'domain' based grouping rather than 'technical' grouping. Domain Based grouping is like 'Commentable', 'Photoable', 'Attendable'. Technical grouping will mean 'ValidationMethods', 'FinderMethods' etc

So Concerns are just a way to use inheritance or interfaces or multiple inheritance? What's wrong with creating a common base class and subclassing from that common base class?

Indeed @Chloe, I some where red, a Rails app with a 'concerns' directory is actually a 'concern'...

You can use the 'included' block to define all your methods and includes: class methods (with def self.my_class_method), instance methods and method calls and directives in the class scope. No need for module ClassMethods

The problem I have with concerns is that they add functionality directly to the model. So if two concerns both implement add_item, for example, you're screwed. I remember thinking Rails was broken when some validators stopped working, but someone had implemented any? in a concern. I propose a different solution: use the concern like an interface in a different language. Instead of defining the functionality, it defines the reference to a separate class instance that handles that functionality. Then you have smaller, neater classes that do one thing...

@aaditi_jain : Please correct small change to avoid misconception. ie "Create a attendable.rd and commentable.rb file in app/models/concerns/event folder" --> attendable.rd has to be attendable.rb Thanks

How to use concerns in Rails 4 - Stack Overflow

ruby-on-rails ruby-on-rails-4 dci
Rectangle 27 10

Used in Rails and could be adapted to any framework:

add a hidden _method parameter to any form that is not GET or POST:

<input type="hidden" name="_method" value="DELETE">

This can be done automatically in frameworks through the HTML creation helper method (e.g. Rails form_tag)

fix the actual form method to POST (<form method="post")

processes _method on the server and do exactly as if that method had been sent instead of the actual POST

http - Are the PUT, DELETE, HEAD, etc methods available in most web br...

http cross-browser browser ajax
Rectangle 27 1

I think you'd need to create a PathResolver that used something other than key order to get the actual file (FileSystemResolver is the default; see action_view/template/resolver.rb; see action_view/template/handlers.rb for the key-order thing I'm referring to). This is unverified, though; sorry :(

I'm not sure how to tell Rails to use a new implementation, though (assuming not just monkey-patching). Using a custom view resolver is as easy as calling append_view_path in the controller class, but I'm not sure if that makes sense for this.

haml - How can I change the order template engines are used in Rails 3...

ruby-on-rails haml erb slim-lang