Question

I've been stuck on this problem for days. First off, I now know this code is horribly wrong. I've been trying to fix it, but it's way more important in the short term that this link is created. In my view (I'm so sorry), I call the create method like this, if a certain condition is met:

index.html.erb (controller: subjects_controller)

<%= Baseline.create(subject_id: sub.subject_id) %>

I do this several times on the page, from several controllers (i.e., FollowUp3Week.create(subject_id: sub.subject_id) works). All of the other controllers work. I've checked, and double checked, every controller action and compared them to each other, and they appear the same.

So instead of creating the record, it leaves something like this instead:

#<Baseline:0x007f944c4f7f80> 

I'm at a bit of a trouble shooting loss. Once again, I know how wrong it is to have these database actions in the view. But I didn't know that when I made the page, and I really need this to function before I can take the time to learn how to rearrange everything through the MVC.

Any advice would be greatly appreciated. Let me know what other code you might want to look at.

EDIT 1. link Creation:

  <% if Baseline.where(subject_id: sub.subject_id).first != nil %> 
    <%= link_to "edit", baseline_path(Baseline.where(subject_id: sub.subject_id).first) %>              
  <% else %>
    <%= Baseline.create(subject_id: sub.subject_id) %>
  <% end %>
Was it helpful?

Solution

First of all, making DB calls in views is a big NO! NO!

Secondly, to answer why you see the output as

#<Baseline:0x007f944c4f7f80>

for

<%= Baseline.create(subject_id: sub.subject_id) %>

You are trying to render an instance of Baseline model. Its just how the instance would be displayed. If you want to display a particular attribute's value in view then just do

<%= Baseline.create(subject_id: sub.subject_id).subject_id %>

Also, this code will not create a link. To create a link you would have to call link_to helper in your view.

What you need to do is, move the Baseline.create call in the controller. Set an instance variable in the action which renders this particular view as below:

def action_name
  @baseline = Baseline.create(subject_id: sub.subject_id)
end

After this in you view you can easily access all the attributes of @baseline instance.

For example:

To access subject_id

<%= @baseline.subject_id %>

To create a link for show page of @baseline, provided you have a RESTful route to show action for baselines

<%= link_to "Some Link", @baseline %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top