Question

I recently converted to Rails 4 and strong params, and I'm having a hard time figuring this out.

My model looks like so:

class Message
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  validates :name, :email, :body, :presence => true

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end

It's my understanding that I don't need a controller containing strong params for this model, because I'm strictly "getting" it. I'm not updating or saving it anywhere, so I don't need to permit any params to be passed through. However, to be sure, I have this controller:

class MessagesController < ApplicationController

  private

  def message_params
      params.require(:message_params).permit(:name, :email, :body)
  end
end

This throws an error:

message = Message.new
message.name = 'test'

NoMethodError: undefined method `name=' for #<Message:0x007f9d620706f0>

My model used to contain this:

attr_accessor :name, :email, :body

And it worked fine. What am I missing in my rails 4 upgrade, and what do I need to change to gain access to these attributes again?

Was it helpful?

Solution

You still do need the attr_accessor defining which attributes your model has.

There's also a ActiveModel::Model module you can include rather than including separate modules:

class Message
  include ActiveModel::Model

  attr_accessor :name, :email, :body

  validates :name, :email, :body, :presence => true

  def persisted?
    false
  end
end

See the ActiveModel documentation for more information.

OTHER TIPS

So you're still going to want to use attr_accessor. You're mixing it up with attr_accessible.
Take a look at this answer: Difference between attr_accessor and attr_accessible

attr_accessor is "is a ruby method that makes a getter and a setter" while attr_accessible is now an unsupported "rails method that allows you to pass in values to a mass assignment: new(attrs) or up update_attributes(attrs)."

You are creating a tableless model. The accessor methods are not created for your model by default. You need to add attr_accessor for the attributes of this specific model explicitly in order to read and write the attributes. Hence, the error.

For models with table, the model class extends from ActiveRecord::Base which takes care of creating the accessor methods for attributes dynamically so you don't specify attr_accesor there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top