1

There are two params and am getting a single one like that

v = (params.require(:service).permit(:title))

This v has a value like this {"title"=>"test,kil"} and I want to get the value of right side to a string, but all in vain. The concept am trying to impose after that i will have @test= "test,kil"

Anyhelp will be great full. am a newbie to Rails.

1
  • You can drop the parens around (params.require(:service).permit(:title)) unless you want pretend it's LISP. Commented Jul 12, 2015 at 8:04

2 Answers 2

1

params in Rails is just a Hash (well kind of).

To access the values of a hash in Ruby you use the square bracket syntax:

v = params.require(:service).permit(:title)
@test = v['title']

Params in Rails are a kind a special hash type called HashWithIndifferentAccess. So we can do both v['title'] or v[:title].

Sign up to request clarification or add additional context in comments.

5 Comments

Normal ruby hashes are specific about the type of a key. { "a" => 2 }[:a] returns nil for example.
further more i am going to split the @test into array after every "," break and then can i pass it to Service.new(@test) in a loop? i.e @again = @test.try(:split,",") @again.each do |kil| Service.new(kil) end
I'm not sure what you asking. Its usually better to ask a new question than to comment with a bunch of follow up questions that don't directly relate to the original question.
Okay am going to post a new question @max
0

You can just do the following:

@test = params.require(:service).permit(:title)[:title]

def create
  @qure = params.require(:service).permit(:level_id)[:level_id]
  @test = params.require(:service).permit(:title)[:title]
  @gain = @test.split(",")

  # Note: You need to use a hash to pass args to the model
  @gain.each do |fil|
    Service.create!(title: fil, level_id: @qure)
  end

  redirect_to root_url
end

I've also used create! in the method but you should consider using save and checking the return value if you want to use validations. The above will raise an error if there are validation issues.

6 Comments

Sorry to ask again can i Split @test into array and then pass it through Service.new(@test), as param?
Yes, you can just split with @test.split(",") and this will give you an array. Is Service an active record object? What are you trying to do here?
Service is an Model. can i pass it to Service.new(@test) in a loop? i.e @again = @test.try(:split,",") @again.each do |kil| Service.new(kil) end
OK so you can't just pass strings to new. I mad an error in my previous comment as I was rushing but you can pass ids to find as an array which is different. To use new you need to pass a hash! I'll update my answer to reflect
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.