5

Rails 4: I'm coming from rails 3.2.x And I have a question. How can I use Strong parameter with no controller.

I have this model:

Track (the only one that has a Controller  )
  has_many :tracksegments, :dependent => :destroy
  has_many :points, :through => :tracksegments
Tracksegment
  belongs_to :track
  has_many :points, :dependent => :destroy
points
  belongs_to :tracksegment

Track is the only one that has a Controller so it has some Strong Parameters.

I want to know where can I put the parameters that belongs to "tracksegment" and "points" In Rails 3.x it's direct in the model but in rails 4 i have no controller for them.

Papouche Guinslyzinho
  • 5,277
  • 14
  • 58
  • 101
  • You need to make sure tracksegment and points are nested under track. Then you can access their parameters in the track controller. See my answer for an example of nested parameter whitelisting. – toolz Jan 31 '14 at 19:16

3 Answers3

8

This might help if you need to use "strong params" outside of controllers:

Use Outside of Controllers

While Strong Parameters will enforce permitted and required values in your application controllers, keep in mind that you will need to sanitize untrusted data used for mass assignment when in use outside of controllers.

For example, if you retrieve JSON data from a third party API call and pass the unchecked parsed result on to Model.create, undesired mass assignments could take place. You can alleviate this risk by slicing the hash data, or wrapping the data in a new instance of ActionController::Parameters and declaring permissions the same as you would in a controller. For example:

raw_parameters = { :email => "john@example.com", :name => "John", :admin => true }
parameters = ActionController::Parameters.new(raw_parameters)
user = User.create(parameters.permit(:name, :email))

https://github.com/rails/strong_parameters

Chris
  • 111
  • 1
  • 2
3

You permit the parameters into whichever controller you are sending them through. It sounds like you are sending them through your track controller, if so you would add them there.

see this question about how to permit nested params Rails 4 - Strong Parameters - Nested Objects

Community
  • 1
  • 1
toolz
  • 871
  • 6
  • 12
2

You need to add the strong parameters just in the controllers. Now in Rails 4, if you do not have any controller, you don't have add attr_accessible.

So, you track controller will be some thing like

def create 
@track = Track.create(track_params)
end

private

def track_params
params.require(:track).permit(:param1, :param2, :param2)
end

Make sure if you have nested attributes then you specify them in your strong parameter method.

Ishank Gupta
  • 1,575
  • 1
  • 14
  • 19