0

I am using rails 4. I have a model that uses validation, but does not store any records. It is only used for a web contact form that sends an email.

I am trying to use strong parameters with this controller/model. Currently I am getting a nomethoderror on my new action. Any ideas? I think it is something to do with my model not being a full blown model.?

Code slimmed down for easy viewing.

model:

class Message
  include ActiveModel::Model
  include ActiveModel::ForbiddenAttributesProtection
end

controller:

class MessagesController < ApplicationController
  def new
    @message = Message.new
  end

  private

    def project_params
      params.require(:message).permit(:name, :email, :content)
    end
end
Keil Miller
  • 71
  • 10

1 Answers1

2

Your project_params needs to be renamed to message_params since you want to allow message in your MessagesController and not project.

Please try:

class MessagesController < ApplicationController
  def new
    @message = Message.new
  end

  private

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

Update:

Also, although you've mentioned "code slimmed down for easy viewing", I should add that you also need to define att_accessor for those permitted attributes as follows:

class Message
  include ActiveModel::Model
  include ActiveModel::ForbiddenAttributesProtection

  attr_accessor :name, :email, :content
end

Please see Louis XIV's answer in this question: "Rails Model without a table"

Community
  • 1
  • 1
vee
  • 38,255
  • 7
  • 74
  • 78
  • Good catch on the message_params. I tried to copy some code from a projects scaffold. I don't understand why I have to add the attr_accessor in Rails 4? Running a scaffold, it doesn't use attr_accessor, and params.require(model).permit(columns) is run with create and update actions. New action only has @project = Project.new and no attr_accessor in model. – Keil Miller Sep 29 '13 at 14:00
  • 1
    @KeilMiller, you must be accessing these attributes in your template file e.g. `new.html.erb`, which is where the NoMethodError originates from. Strong Parameters directly replaces `attr_accessible` which was used for mass assignment prior Rails4. We use `attr_accessor`, a ruby method, to define getters and setters for attributes. Please have a look on difference between `attr_accessor` and `attr_accessible`. – vee Sep 29 '13 at 14:29
  • I think I understand now. Thank you very much for your clear explanation. This [question/answer](http://stackoverflow.com/questions/3136420/difference-between-attr-accessor-and-attr-accessible) was also useful for the differences between attr_accessible and attr_accessor. – Keil Miller Sep 29 '13 at 16:30